JavaScript moving element in the DOM

Viewed 162389

Let's say I have three <div> elements on a page. How can I swap positions of the first and third <div>? jQuery is fine.

7 Answers

.before and .after

Use modern vanilla JS! Way better/cleaner than previously. No need to reference a parent.

const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
const div3 = document.getElementById("div3");

div2.after(div1);
div2.before(div3);

All modern browsers are supported!

Browser Support

Related