How can I inline each loop using JQuery to get specific li elements?
What I am trying to do is go through ul
which are organized like
<ul class="some-ul">
<li class="some-li"></li>
<li></li>
<li></li>
<li class="some-li"></li>
</ul>
<ul class="some-ul">
<li class="some-li"></li>
<li></li>
<li></li>
<li></li>
</ul>
<ul class="some-ul">
<li class="some-li"></li>
<li class="some-li"></li>
<li class="some-li"></li>
<li class="some-li"></li>
</ul>
and do something with a li
class some-li
and something else with li
that do not have that class. So it would be equivalent to
$('ul.some-class li.some-class').each(function() {
// do something
});
$('ul.some-class li:not(.some-class)').each(function() {
// do something else
});
except i want to do it like
$('ul.some-class').each(function() {
// loop through the list elements of this list
});
but I don't know how to build this inner loop. Is this possible, and if so, which tool should I use?
source to share
Inside .each
this
will be the current iteration element. Then you can use $(this).find()
to find elements within it:
$('ul.some-ul').each(function(i, ul) {
$(ul).find("li").each(function(j, li) {
// Now you can use $(ul) and $(li) to refer to the list and item
if ($(li).hasClass('some-li')) {
...
}
});
});
source to share
Scroll through all <li>
and use hasClass()
to make sure they match the class you want or not and react accordingly
$('.some-ul').children().each(function(){
// "this" is current li
if ( $(this).hasClass('some-li') ){
$(this).doSomeClassThing();
} else {
$(this).doNoClassThing();
}
});
One pass and you're done
source to share