Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting, removing, and appending elements using jQuery isn't working in IE

This function that sorts my links works like a charm on Chrome/Safari/Firefox but not in IE. Can someone tell me why?

Symptom: everything disappears (line2) nothing appears (line3)

HTML:

 <div class="genres">
   <a title="90 items" href="?genre=absurdism"><span>absurdism</span></a>
   <a title="83 items" href="?genre=action"><span>action</span></a>
   <a title="322 items" href="?genre=adult"><span>adult</span></a>
   <a title="2974 items" href="?genre=adventure"><span>adventure</span></a>
   <a title="106 items" href="?genre=about+comics"><span>about comics</span></a>
 </div>

SCRIPT:

sorted = $('.genres a').sort(function(a, b) {
    return a.innerHTML > b.innerHTML
});
$('.genres').html('');
sorted.each(function(i, a) {
    $('.genres').append(a)
});

Fiddle: http://jsfiddle.net/MWkJg/2/

The online page of this code is on http://www.lambiek.net/webshop.html (click on "genre" button)

like image 218
Dirk Zaal Avatar asked Oct 03 '22 14:10

Dirk Zaal


1 Answers

You need to replace this:

$('.genres').html('');

with

$('.genres').empty();

html uses the innerHTML property to remove contents, and this is handled inconsistently among browsers as you have just seen. empty, however, uses the removeChild method, and works consistently across browsers. (Incidentally jQuery 2.0 uses textContent.)

Also, for your sort method to work consistently, it needs to return a numeric value:

var sorted = $('.genres a').sort(function(a, b) {
    return a.innerHTML < b.innerHTML ? -1 :
            a.innerHTML === b.innerHTML ? 0 :
            1;
});

FIDDLE

like image 193
1983 Avatar answered Oct 06 '22 03:10

1983