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,
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]);
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With