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.
To move element in the DOM in JavaScript, we can use the before and after methods. const div1 = document. getElementById("div1"); const div2 = document. getElementById("div2"); const div3 = document.
The DOM stands for Document Object Model. It can simply be understood as a tree of nodes created by the browser. Each of these nodes has its own properties and methods which can be manipulated using JavaScript. The ability to manipulate the DOM is one of the most unique and useful abilities of JavaScript.
There's no need to use a library for such a trivial task:
var divs = document.getElementsByTagName("div"); // order: first, second, third divs[2].parentNode.insertBefore(divs[2], divs[0]); // order: third, first, second divs[2].parentNode.insertBefore(divs[2], divs[1]); // order: third, second, first
This takes account of the fact that getElementsByTagName
returns a live NodeList that is automatically updated to reflect the order of the elements in the DOM as they are manipulated.
You could also use:
var divs = document.getElementsByTagName("div"); // order: first, second, third divs[0].parentNode.appendChild(divs[0]); // order: second, third, first divs[1].parentNode.insertBefore(divs[0], divs[1]); // order: third, second, first
and there are various other possible permutations, if you feel like experimenting:
divs[0].parentNode.appendChild(divs[0].parentNode.replaceChild(divs[2], divs[0]));
for example :-)
Trivial with jQuery
$('#div1').insertAfter('#div3'); $('#div3').insertBefore('#div2');
If you want to do it repeatedly, you'll need to use different selectors since the divs will retain their ids as they are moved around.
$(function() { setInterval( function() { $('div:first').insertAfter($('div').eq(2)); $('div').eq(1).insertBefore('div:first'); }, 3000 ); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With