0

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

GeorgeBT1902
  • 195
  • 2
  • 14

2 Answers2

1

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 ids 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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 2
    I don't understand the down vote - Must be some angry user who didn't answer quick enough. It worked perfect so thank you! – GeorgeBT1902 Dec 10 '18 at 20:44
-1

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/

genhernandez
  • 453
  • 1
  • 5
  • 19