I don't even know how to explain my problem - that's where the weird title es from.
I have a ul
wrapping another ul
like the sample underneath.
<ul class="event-items">
<li class="year 2012"></li>
<li class="year 2011"></li>
<li class="year 2010">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li class="year 2010"></li>
…
So each li.year
has another <ul>
with multiple children inside.
Now my problem:
I wonder how I can run through each
li.year
individually.
Right now I'm doing this …
$('ul.event-items li.year ul li').each(function(i) {
if ( i % 4 == 0 ) $(this).addClass('clearLeft');
});
However this each
loop runs through a ALL <li>
s. I wonder how I can run through each li:year li
individually. Sounds weird right?
So I actually want to loop through each of li.year
individually so that my i
count always starts fresh inside each li.year
I don't even know how to explain my problem - that's where the weird title es from.
I have a ul
wrapping another ul
like the sample underneath.
<ul class="event-items">
<li class="year 2012"></li>
<li class="year 2011"></li>
<li class="year 2010">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li class="year 2010"></li>
…
So each li.year
has another <ul>
with multiple children inside.
Now my problem:
I wonder how I can run through each
li.year
individually.
Right now I'm doing this …
$('ul.event-items li.year ul li').each(function(i) {
if ( i % 4 == 0 ) $(this).addClass('clearLeft');
});
However this each
loop runs through a ALL <li>
s. I wonder how I can run through each li:year li
individually. Sounds weird right?
So I actually want to loop through each of li.year
individually so that my i
count always starts fresh inside each li.year
3 Answers
Reset to default 5Use nested loops to iterate over the children of each inner ul
separately:
$('ul.event-items li.year ul').each(function() {
$("li", this).each(function(i) {
if (i % 4 == 0)
$(this).addClass('clearLeft');
});
});
Is this what you mean?
$('ul.event-items li.year').each(function(i) {
if ( i % 4 == 0 ) $(this).find('ul li').addClass('clearLeft');
});
Alternatively, you could also use .index()
.
$('ul.event-items li.year ul li').each(function() {
var $this = $(this);
if ( $this.index() % 4 == 0 ) $this.addClass('clearLeft');
});
.index()
will return you the index of each li
in relation to its parent, ul
.