How to order divs by id in javascript?

Issue

I have this HTML code:

<div id="main">
  <div id="dv_7">...</div>
  <div id="dv_1">...</div>
  <div id="dv_8">...</div>
  <div id="dv_4">...</div>
  <div id="dv_11">...</div>
  <div id="dv_2">...</div>
</div>

How to order the divs in the maindiv with javascript? I have no idea 🙁

thanks in advance,

Solution

How about:

var main = document.getElementById( 'main' );

[].map.call( main.children, Object ).sort( function ( a, b ) {
    return +a.id.match( /\d+/ ) - +b.id.match( /\d+/ );
}).forEach( function ( elem ) {
    main.appendChild( elem );
});

Live demo: http://jsfiddle.net/ZEKrH/6/

(You’ll need to shim those array methods for IE8.)

Answered By – Šime Vidas

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.