Reputation: 7688
I am really lost with trying to order an ul list by the span in the li.
I have this next structure
<ul id="videosList">
<li class="response1">
<a href="link"><img src="moon" /><span>Alex breaking bad</span>
<li>
<li class="response1">
<a href="link"><img src="moon" /><span>Jason playing piano</span>
<li>
<li class="response1">
<a href="link"><img src="moon" /><span>Jenny skying</span>
<li>
<li class="response1">
<a href="link"><img src="moon" /><span>Chuck norris</span>
<li>
<li class="response1">
<a href="link"><img src="moon" /><span>Zyxwaa</span>
<li>
<li class="response1">
<a href="link"><img src="moon" /><span>Realtek</span>
<li>
<li class="response2">
<a href="link"><img src="moon" /><span>Bad alex breaking</span>
<li>
<li class="response2">
<a href="link"><img src="moon" /><span>Piano playing Jason</span>
<li>
<li class="response2">
<a href="link"><img src="moon" /><span>Skying Jenny</span>
<li>
<li class="response2">
<a href="link"><img src="moon" /><span>Norris chuck</span>
<li>
<li class="response2">
<a href="link"><img src="moon" /><span>Intel</span>
<li>
</ul>
I have that list generated from some uploaded videos and separated because respnse1 brings videos from X database and response brings videos from Y database. What I want to do is to order the list by the content of the SPAN in LI.
I've tried a few things from Google and Stack Overflow but I couldn't adapt any 1 to fit what I need.
So that's it, how can I order a list with JavaScript/jQuery by the content of SPAN in LI?
Upvotes: 2
Views: 826
Reputation: 764
it works!...
var list = $("ul#videosList");
var desc= false;
list.append(list.children().get().sort(function(a, b) {
var aProp = $(a).find("span").text(),
bProp = $(b).find("span").text();
return (aProp > bProp ? 1 : aProp < bProp ? -1 : 0) * (desc ? -1 : 1);
}));
Upvotes: 2
Reputation: 9445
If you're using jQuery, refer this extension which helps you sorting DOM elements with a custom comparer function. It works like this:
$('#videosList').sortElements(function(a, b){
return $(a).text() > $(b).text() ? 1 : -1;
});
Then, the list items are sorted alphabetically by their captions.
Upvotes: 0