How to sort a list based on the number within each LI.span?
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>
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>