I'd like to use Jquery to sort multiple lists alphabetically. I've come across Alphabetize a list using JS or jQuery as a solution for one list. However, it is not applying when I have multiple lists on the same page.
I have 2 lists here, which I would like to be listed alphabetically, but separated into 2 lists. I don't want them combined together into 1 list.
<div class="alphabet">
<b>Fruit</b>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Banana</li>
</ul>
<b>Vegetables</b>
<ul>
<li>Lettuce</li>
<li>Carrot</li>
<li>Cucumber</li>
</ul>
</div>
and this
$(".alphabet ul").each(function(){
$('.alphabet li').sort(function(a, b) {
var aText = $(a).text(), bText = $(b).text();
return aText < bText ? -1 : aText > bText ? 1 : 0;
}).appendTo(this);
});
JSfiddle demo: https://jsfiddle.net/1efm8aeb/
I believe I'm using .each() wrong, however I am unsure how to fix this. Thanks!
Here's the updated fiddle: https://jsfiddle.net/1efm8aeb/1/
Basically you are missing the fact that once inside the .each
of .alphabet ul
selector, you shouldn't select the list items using .alphabet li
- as it returns all 6 items instead of just the 3.
Instead, you should search for list items only among the children of the ul
being iterated.
This can be done by modifying the code as:
$(".alphabet ul").each(function(){
$(this).find('li').sort(function(a, b) {
var aText = $(a).text(), bText = $(b).text();
return aText < bText ? -1 : aText > bText ? 1 : 0;
}).appendTo(this);
});