Move Element from One Location to Another with JavaScript

Often times we can move elements around on a page with CSS, but sometimes that’s just not a good solution when elements need to taken across an entire screen.

Here’s an example so you can see what I mean. A user wants to move the Amazon Pay section from down at the bottom of the checkout page to the top.

Using CSS positioning we could do that, but it would be tricky to have it look right across screen sizes.

Fortunately, we can use JavaScript to make the move for us. Since WordPress comes bundled with jQuery we’ll use this library’s built-in functions to handle it.

What you need to do is find out the class or ID of the item that you want to move and then the class/ID of an element right after where you want it to go. In our example, the Amazon Pay has a class wc-amazon-payments-advanced-info we can use to grab it. Now to move it to the top of the page, we can use these classes form-row and place-order.

jQuery comes with a function called prependTo which takes the specified element and adds it right before whatever other element you specify. Using it and our classes, we can write one quick line of JavaScript to move this.

jQuery(".wc-amazon-payments-advanced-info").prependTo(".form-row.place-order");

When I apply that to the page, the Amazon Pay button is moved from the area where the other payment methods are to the very top of the checkout form.

Also, as far as the browser is concerned, the element is really in that position. So the other items on the page will react as if it’s always been there.

It’s a simple solution that you can use when CSS positioning just isn’t enough. Even if someone has JavaScript disabled, the worst that will happen is the element won’t be moved.

So now you have a new way to rearrange elements on a page. Enjoy!


Leave a Reply

%d bloggers like this: