Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .sort() and .data() to sort HTML elements in IE11 and Edge

I used this question (jQuery sort elements using data id) to get a lot of work done on a project I'm doing.

The top voted answer mentions that using jQuery;s .data() is required if I need it to work in IE10 and below. I haven't tested it in any of those browsers, but I have found that it does not work in IE11 or Edge.

Here's the jsfiddle that works just fine in Chrome for me: http://jsfiddle.net/4o771n7o/

HTML

<div class="clist">
    <div data-sid=1>1</div>
    <div data-sid=4>4</div>
    <div data-sid=3>3</div>
    <div data-sid=1>1</div>
    <div data-sid=4>4</div>
    <div data-sid=2>2</div>
    <div data-sid=1>1</div>
</div>

Javascript

$('.clist div').sort(function(a,b) {
     return $(a).data('sid') > $(b).data('sid');
}).appendTo('.clist');
like image 487
jkupczak Avatar asked Nov 17 '25 05:11

jkupczak


2 Answers

The sort function is bad; I'm not sure why it works for any other browser. Working JSFiddle:

http://jsfiddle.net/0m75k1fm/

The sort function should return a number, not a boolean:

$('.clist div').sort(function(a,b) {
     return parseInt($(a).data('sid'), 10) - parseInt($(b).data('sid'), 10);
}).appendTo('.clist');
like image 167
Jacob Avatar answered Nov 18 '25 20:11

Jacob


You can use

$('.clist div').sort(function(a,b) {
     return $(a).attr('data-sid') > $(b).attr('data-sid') ? 1 : -1;
}).appendTo('.clist');

Works in edge

like image 41
Evgeny Avatar answered Nov 18 '25 19:11

Evgeny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!