How can I reorder elements with JavaScript?

There is no catch-all way of reordering elements with css.

You can inverse their order horizontally by floating them all to the right. Or you can position them absolutely relative to the body or some other containing element – but that comes with severe limitations regarding the size of the elements, and positioning relative to other elements on the page.

Short answer: You can only achieve this in a very limited set of circumstances. Reordering elements is best done in markup.

If you have no control over the html, you could use javascript. Here using jQuery:

$("#div2").insertAfter("#div3");
$("#div1").prependTo("#div2");

I certainly don’t recommend that unless your hands are tied. It will be harder to maintain, and for your end users it will make your page “jerk around” while its setting up the page.

Leave a Comment