views:

40

answers:

2

Trying a bunch of solutions with no workable results. I have code that takes the value of the span and creates an ID for the LI. I then want to sort these LI's DESCENDING based on the LI's ID. Help? Thanks!

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="dumb">
    <li>cello<span>2987</span></li>
    <li>zello<span>1723</span></li>
    <li>aello<span>3476</span></li>
</ul>
<script type='text/javascript' src='JQUERY INCLUDE'></script> 
<script type="text/javascript"> 
$(document).ready(function() {
    $('ul li span').each(function(){
        var pubValue = $(this).html();
        $(this).parent().attr('id', pubValue);
    });
});
</script>
</body>
</html>
+2  A: 

Let's assume your li nodes had ids.

<ul id="test">
   <li id="4112">blub</li>
   <li id="1422">blaaah</li>
   <li id="6640">hmmmm</li>
   <li id="2221">one more</li>
</ul>

Then you could just call javascripts native array .sort() method, since jQuery wrapped sets are hold in Arrays:

$(function(){
    var elems = $('#test').children('li').remove();
    elems.sort(function(a,b){
        return parseInt(a.id) > parseInt(b.id);
    });
    $('#test').append(elems);
});

Working example: http://www.jsfiddle.net/3uYUq/

jAndy
That was perfect, thanks jAndy!
joe
Apparently in Safari, you need `-` instead of `>`.
patrick dw
@patrick: interesting, so you would need to change the order if you want to have an ascending list?
jAndy
jAndy - That appears to be the case.
patrick dw
A: 

jAndy beat me to the punch. Here's mine.

$(function() {
  $("li").sort(function(left, right) {
    return parseInt($(left).attr("id")) - parseInt($(right).attr("id"));
  }).each(function() { $("ul").append($(this)); });
});

I'll add that you need

$(function() {

for your IE6 users because IE6 will crash if you try to remove elements from the dom before their parent elements load.

Also, .remove() is redundant because .append() takes care of that.

Dave Aaron Smith