Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript moving element in the DOM

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.

like image 277
core Avatar asked Sep 01 '09 17:09

core


People also ask

How do you move elements in DOM?

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.

Can JavaScript manipulate DOM?

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.


2 Answers

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 :-)

like image 107
NickFitz Avatar answered Sep 26 '22 21:09

NickFitz


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 ); }); 
like image 26
tvanfosson Avatar answered Sep 22 '22 21:09

tvanfosson