How to order divs by id in javascript?


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>

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

thanks in advance,


How about:

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

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

Live demo:

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

Answered By – Šime Vidas

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.