Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
</div>

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

thanks in advance,

like image 787
Danny Fox Avatar asked Mar 19 '12 22:03

Danny Fox


2 Answers

Hope this helps. Updated the id to account for alphabetical ordering 1 and 11.

<div id="main">
  <div id="dv_07">7...</div>
  <div id="dv_01">1...</div>
  <div id="dv_08">8...</div>
  <div id="dv_04">4...</div>
  <div id="dv_11">11...</div>
  <div id="dv_02">2...</div>
</div>​

jQuery option:

var mylist = $('#main');
var listitems = mylist.children('div').get();
listitems.sort(function(a, b) {
    var compA = $(a).attr('id').toUpperCase();
    var compB = $(b).attr('id').toUpperCase();
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) {
    mylist.append(itm);
});​

Javascript option:

var mylist = document.getElementById('main');
var divs = mylist.getElementsByTagName('div');
var listitems = [];
for (i = 0; i < divs.length; i++) {
        listitems.push(divs.item(i));
}
listitems.sort(function(a, b) {
    var compA = a.getAttribute('id').toUpperCase();
    var compB = b.getAttribute('id').toUpperCase();
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
for (i = 0; i < listitems.length; i++) {
    mylist.appendChild(listitems[i]);
}​
like image 162
Coding101 Avatar answered Sep 27 '22 21:09

Coding101


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.)

like image 44
Šime Vidas Avatar answered Sep 27 '22 21:09

Šime Vidas