Categories
JavaScript Answers

How to move element in the DOM in JavaScript?

Spread the love

Sometimes, we want to move element in the DOM in JavaScript.

In this article, we’ll look at how to move element in the DOM in JavaScript.

How to move element in the DOM in JavaScript?

To move element in the DOM in JavaScript, we can use the before and after methods.

For instance, we write

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

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

to select 3 divs with getElementById.

Then we call div2.after with div1 to insert div1 after div2.

And we call div2.before with div3 to insert div3 before div2.

Conclusion

To move element in the DOM in JavaScript, we can use the before and after methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *