how do I sort li tag using ul tag in JQuery? [dupl

2019-08-31 02:33发布

问题:

This question already has an answer here:

  • jQuery order by date in data attribute 3 answers
  • What is the easiest way to order a <UL>/<OL> in jQuery? 3 answers
<ul id ="sort">
    <li id = '2014-02-07'>tralala<li>
    <li id = '2013-02-09'>tralala<li>
    <li id = '2014-01-04'>tralala<li>
    <li id = '2011-09-05'>tralala<li>
</ul>

I want that the result to be :

<ul id ="sort">
    <li id = '2014-02-07'>tralala<li>
    <li id = '2014-01-04'>tralala<li>
    <li id = '2013-02-09'>tralala<li>
    <li id = '2011-09-05'>tralala<li>
</ul>

I want to sort desc the li using the id in JQuery or Javascript . Thx

回答1:

You could do this :

var list = $('#sort'),
    items = list.children().get();
list.append(items.sort(function(a, b){
    return new Date(b.id) - new Date(a.id);
}));

Here is a demo : http://jsfiddle.net/wared/EE5HB/.