简体   繁体   中英

Order divs by ID in Javascript

I have a bunch of divs that I would like to order from lowest to highest based on their ID. The IDs, however, are decimal numbers up to 5DP.

They look like this:

<div id="main">
  <div id="1.6125">...</div>
  <div id="1.585">...</div>
  <div id="1.60125">...</div>
  <div id="1.59125">...</div>
  <div id="1.62625">...</div>
</div>

I've seen this question: How to order divs by id in javascript? But when I change the askers example to be decimal numbers it does not order the divs for me.

Any help would be appreciated, either jQuery or JS is fine with me.

Many thanks,

G

Select the .children of the #main div, then sort() them by extracting the id of each and comparing the difference, then append them to #main so that they'll be in order in the DOM. The - in the sort function will automatically cast the string id s to numbers:

 const main = document.querySelector('#main'); const divs = [...main.children]; divs.sort((a, b) => a.id - b.id); divs.forEach(div => main.appendChild(div)); 
 <div id="main"> <div id="1.6125">1.6125</div> <div id="1.585">1.585</div> <div id="1.60125">1.60125</div> <div id="1.59125">1.59125</div> <div id="1.62625">1.62625</div> </div> 

The problem is how the other post is comparing the ids.

Try this:

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

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

Preview: http://jsfiddle.net/x7gesv68/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM