I'm trying to iterate through all the elements with a specific class to sort their children based on their value attributes. I need to sort the children separately for each parent elements.
Html structure :
<ul class="parentClass">
<li value="1">...</li>
<li value="10">...</li>
<li value="8">...</li>
</ul>
<ul class="parentClass">
<li value="8">...</li>
<li value="29">...</li>
<li value="5">...</li>
</ul>
JS code :
function sortAll() {
$(".parentClass").each(function() {
var items = $(this).children("li").sort(function(a, b) {
var vA = $("li", a).attr("value");
var vB = $("li", b).attr("value");
return (vA > vB) ? -1 : (vA > vB) ? 0 : 1;
});
$(this).append(items);
});
}
What I'm trying to get :
<ul class="parentClass">
<li value="10">...</li>
<li value="8">...</li>
<li value="1">...</li>
</ul>
<ul class="parentClass">
<li value="29">...</li>
<li value="8">...</li>
<li value="5">...</li>
</ul>
I think I misunderstood something with iteration. Could you help me to figure out my mistake?
I would also let you know that some <li>
elements could have the same value.
Solution :
function sortAll() {
$(".parentClass").each(function() {
var items = $(this).children("li").sort(function(a, b) {
var vA = $(a).attr("value");
var vB = $(b).attr("value");
return (vA > vB) ? -1 : (vA > vB) ? 0 : 1;
});
$(this).append(items);
});
}