Reputation: 11207
I'm trying to sort the list of LI's based on the number that's in the span within each LI. I've looked at plugins that can do this but that's not what I want.
Can someone show me how you would sort a simple list how I stated above? I really don't have any idea where to even start, I don't know if it's complex or simple.
Here is my code:
ul {
width: 200px;
background-color: #252525;
padding: 10px;
}
li {
background-color: #353535;
margin: 10px;
padding: 5px;
color: #fff;
}
li span {
float: right;
}
<ul>
<li> Cups
<span>12</span>
</li>
<li> Plates
<span>18</span>
</li>
<li> Forks
<span>03</span>
</li>
<li> Knives
<span>06</span>
</li>
<li> Bowls
<span>08</span>
</li>
</ul>
Upvotes: 9
Views: 10299
Reputation: 3873
You should fill an array with all the <li>
elements, sort this array using sort()
, then empty()
the list add append()
the sorted elements.
Something like this :
$("#doSort").click(function() {
// store the li items
var items = $('ul li').get();
items.sort(function(a, b) {
var valueA = $(a).find("span").text();
var valueB = $(b).find("span").text();
if (valueA < valueB) return -1;
if (valueA > valueB) return 1;
return 0;
});
// clear the list and re-add sorted items on button click
$("ul").empty().append(items);
});
ul {
width: 200px;
background-color: #252525;
padding: 10px;
}
li {
background-color: #353535;
margin: 10px;
padding: 5px;
color: #fff;
}
li span {
float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li> Cups
<span>12</span>
</li>
<li> Plates
<span>18</span>
</li>
<li> Forks
<span>03</span>
</li>
<li> Knives
<span>06</span>
</li>
<li> Bowls
<span>08</span>
</li>
</ul>
<button id="doSort">Sort this list!</button>
Upvotes: 3
Reputation: 16624
Here is what you should use:
function sortEm(a, b) {
return parseInt($('span', a).text()) < parseInt($('span', b).text()) ? 1 : -1;
}
$('li').sort(sortEm).prependTo($('ul#test'));
ul {
width: 200px;
background-color: #252525;
padding: 10px;
}
li {
background-color: #353535;
margin: 10px;
padding: 5px;
color: #fff;
}
li span {
float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test">
<li> Cups
<span>12</span>
</li>
<li> Plates
<span>18</span>
</li>
<li> Forks
<span>03</span>
</li>
<li> Knives
<span>06</span>
</li>
<li> Bowls
<span>08</span>
</li>
</ul>
Upvotes: 6