Using JavaScript to Move an Element Before Another Element on your Page

How to move an element on your page Before an element with javascript.

First you need to define the variables. There are three variable that are required to do this.

  1. Locate the element you want to move. In this instance we want to move the side bar.
  2. Locate the Parent element. This is the “Div” (or tag) that surround the Child element you want to add the new element above.
  3. Finally, locate the child element that you want to add above.
var sideBar = document.querySelector("#sidebar");
var tarP = document.querySelector("#main").getElementsByTagName('div')[1];    
var tar = document.getElementsByClassName('woocommerce-tabs wc-tabs-wrapper')[0];

Locating all the elements is that hardest part and so if your script is not working then this is why.

Finally, the function where the magic happens.

tarP.insertBefore(sideBar, tar);

Leave a Reply