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.

- 176,118
- 18
- 189
- 202

- 32,451
- 45
- 138
- 193
7 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 :-)

- 34,537
- 8
- 43
- 40
-
18True, but it's hard to argue with the elegance and readability that something like jQuery provides - not to mention the enhanced capabilities out of the box. – Crazy Joe Malloy Sep 01 '09 at 17:56
-
13Yes, but who only does this one thing? – tvanfosson Sep 01 '09 at 18:29
-
1... or only has 3 divs on the page – Ryan Florence Sep 01 '09 at 18:41
-
43@everybody: the original question asked how to swap the third and first divs on a page that had three divs. That was the question I answered. If the OP had a more complex question, they should have asked it, and they would have got a more complex answer ;-) – NickFitz Sep 02 '09 at 09:21
-
2would this break event handlers attached to those elements? – Martin Jun 05 '14 at 22:40
-
34If anyone looking for this in 2014, please consider this answer. jQuery WAS useful back then, but now it's no so useful anymore, because browsers are standardized, so no need to add a 80 kb library just to do such a simple task. Also, you don't get to know what the DOM really is until you try it without jQuery :) – gustavohenke Jul 22 '14 at 02:18
-
1I think there is a typo, twice, in code comments showing // order: third, second, third. The element third is showed twice. Please update your answer if this is the case. – Jean Vincent Jan 10 '16 at 21:55
-
@NickFitz once you append element for example from one parent to another parent, it doesnt need to be removed from old parent? its simply appended so it means its moved to new parent? – Roxy'Pro Jan 03 '19 at 21:36
-
1@Roxy'Pro That's correct: a node can only have one parent, so it doesn't need to be explicitly detached from its previous parent when appended to the new one. – NickFitz Jan 16 '19 at 15:00
-
1@JeanVincent Oops, you're right! Fixed now; sorry about that :-) – NickFitz Jan 16 '19 at 15:02
-
@Martin: No, the event handlers should remain attached to the nodes. – NickFitz Jan 16 '19 at 15:20
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 );
});

- 524,688
- 99
- 697
- 795
-
1@Ionut -- the point being that it depends on the relative positioning of the elements. Once you change the order you can no longer find the first and third by their ids and need to work out another way. My answer was only meant to illustrate the functionality of the methods to accomplish the requested task, not be a comprehensive solution to swapping the first and third divs in a set an arbitrary number of times. – tvanfosson Sep 01 '09 at 18:15
-
Hi guys, a quick question: Is there an easy way to reset back to the original Dom state once the above jquery function has been complete? – Vikita Mar 07 '13 at 15:42
-
@Vikita - yes, save the original HTML then restore it. You may have to reapply any handlers if they've been directly applied instead of delegated to a higher element. For example, `var html = $('#container').html(); ...; $('#container').html(html);` – tvanfosson Mar 07 '13 at 15:49
.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!

- 42,564
- 15
- 187
- 127
-
-
22You shouldn't have to write less maintainable code to support people on browsers that are old or don't conform to standards. Unless you work in enterprise, few users will miss out – Gibolt Dec 09 '17 at 18:13
-
Other methods work just as well in regards to maintainability, especially when wrapping in a nice clean function. I'm all for writing modern code, but this is bleeding edge. It's great to know what future holds, but as much as I dislike anything related to IE - it's important to _know_ what the impact of your decisions is. In this case - a broken web app in any IE browser. If that's okay with you - great! I added the comment just to inform anyone googling this :) – pyronaur Dec 11 '17 at 09:44
-
2
-
12In a year, that number will be closer to 10%. It is mostly enterprise, government, and older mobile devices. This usually means non-personal devices or less technically inclined users. Answers should be forward looking so we aren't stuck developing in 2009. – Gibolt Dec 12 '17 at 16:17
-
5Here in the future, Microsoft no longer support IE (though still haunts developers in their sleep I'm sure), so this is the best and easiest answer to follow :) – wickywills Mar 04 '21 at 12:42
jQuery.fn.swap = function(b){
b = jQuery(b)[0];
var a = this[0];
var t = a.parentNode.insertBefore(document.createTextNode(''), a);
b.parentNode.insertBefore(a, b);
t.parentNode.insertBefore(b, t);
t.parentNode.removeChild(t);
return this;
};
and use it like this:
$('#div1').swap('#div2');
if you don't want to use jQuery you could easily adapt the function.

- 1,023,142
- 271
- 3,287
- 2,928
var swap = function () {
var divs = document.getElementsByTagName('div');
var div1 = divs[0];
var div2 = divs[1];
var div3 = divs[2];
div3.parentNode.insertBefore(div1, div3);
div1.parentNode.insertBefore(div3, div2);
};
This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.
What standards peculiarities does it rely on?
insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.

- 1
- 1

- 176,118
- 18
- 189
- 202
Jquery approach mentioned on the top will work. You can also use JQuery and CSS .Say for e.g on Div one you have applied class1 and div2 you have applied class class2 (say for e.g each class of css provides specific position on the browser), now you can interchange the classes use jquery or javascript (that will change the position)

- 1,095
- 1
- 13
- 20
Sorry for bumping this thread I stumbled over the "swap DOM-elements" problem and played around a bit
The result is a jQuery-native "solution" which seems to be really pretty (unfortunately i don't know whats happening at the jQuery internals when doing this)
The Code:
$('#element1').insertAfter($('#element2'));
The jQuery documentation says that insertAfter()
moves the element and doesn't clone it

- 217,595
- 99
- 455
- 496

- 1