Reorder Divs

Question!

How would I go about reordering divs without altering the HTML source code?

example, I want divs to appear in order #div2, #div1, #div3, but in the HTML they are:

<div id="#div1"></div>  
<div id="#div2"></div>  
<div id="#div3"></div>

Thanks!

By : Alexandre


Answers

Since now flexbox is widely supported you can also use it to reorder divs using css only:

<div id="container">
    <div id="div1">1</div>  
    <div id="div2">2</div>  
    <div id="div3">3</div>
</div>

And css:

#container{
  display: flex;
  flex-direction: column;
}

#div2{
  order:2
}

#div3{
  order:1
}

It would display:

1
3
2

You can try it on this fiddle.

By : yariash


I would use Javascript to traverse the nodes accordingly. If you want to use a library like jQuery, you can use the above suggestions. If you'd prefer not to have the bloat, use the following simple and minimalistic solution...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Test</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
      function swapSibling(node1, node2) {
        node1.parentNode.replaceChild(node1, node2);
        node1.parentNode.insertBefore(node2, node1); 
      }

      window.onload = function() {
        swapSibling(document.getElementById('div1'), document.getElementById('div2'));
      }
    </script>
  </head>
  <body>
    <div id="div1">1</div>
    <div id="div2">2</div>
    <div id="div3">3</div>
  </body>
</html>

Best regards...

EDIT: Changed function name from swapNode to swapSibling, as I am fairly certain this will only work with nodes that have the same parent.



You could do, in Javascript:

function reOrder() {
  divOne = document.getElementById('#div1');
  divTwo = document.getElementById('#div2');
  divThree = document.getElementById('#div3');
  container = divOne.parentNode;
  container.appendChild(divTwo);
  container.appendChild(divOne);
  container.appendChild(divThree);
}

Edit: Fixed typo in IDs.

By : user64640


This video can help you solving your question :)
By: admin