1

lets say I have html:

<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>

how would I in javascript and not jquery reorder these divs to:

<div id="1">1</div>
<div id="3">3</div>
<div id="2">2</div>
2
  • what order... any random or specific. Commented Sep 8, 2015 at 12:48
  • I want to move div 3 to between div 1 and 2 Commented Sep 8, 2015 at 12:48

2 Answers 2

6

You can use display:flex and the order css (I had to add a letter before the number for your id as SO didn't seem to like it for the css)

.container {display:flex; flex-direction:column}
#s1 {order:1;}
#s2 {order:3;}
#s3 {order:2;}
<div class="container">
  <div id="s1">1</div>
  <div id="s2">2</div>
  <div id="s3">3</div>
</div>

More information about order

More information about flex

Update

Sorry read the question wrong - thought you wanted to do it without js

var div = document.getElementById('3')

div.parentNode.insertBefore(div, document.getElementById('2'))
      <div id="1">1</div>
      <div id="2">2</div>
      <div id="3">3</div>

Sign up to request clarification or add additional context in comments.

Comments

0

The solution given by the duplicate questions are incorrect because they make the assumption that the elements are next to each other. But even in this simple example, there is a text node containing white-space between the elements.

Given that the two elements are not nested, you can use this to swap two elements:

function swapElements (first, second) {
    var tmpNode = document.createElement('div');
    tmpNode.setAttribute('id', '_tmp');

    var firstParent = first.parentNode;
    firstParent.insertBefore(tmpNode, first);
    second.parentNode.insertBefore(second, first);
    firstParent.insertBefore(second, tmpNode);
    firstParent.removeChild(tmpNode);
}

Use it like:

var first = document.querySelector('#1');
var second = document.querySelector('#2');
swapElements(first, second);

1 Comment

what is the use of tmpNode in the process? is it ok to just remove that part in the function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.