Derek Bess Derek Bess - 6 months ago 24
jQuery Question

How to iterate through each parent list items in jquery?

I just started working with jQuery and I'm running into a bit of a snag with iterating through each parent UL's list items.

I have a simple accordion menu where I'm adding transition-delay inline style to each individual list item. The issue I have is that I'm not sure how to iterate through each set of parent's list items.

Below is an example of what is occurring on every list item.

<ul class="sub-menu">
<li style="transition-delay: 0ms;></li>
<li style="transition-delay: 25ms;>
<ul class="sub-menu">
<li style="transition-delay: 50ms;>
<li style="transition-delay: 75ms;>
<li style="transition-delay: 100ms;>
</ul>
</li>
<li style="transition-delay: 125ms;></li>
<li style="transition-delay: 150ms;></li>
<li style="transition-delay: 175ms;></li>
</ul>


This is what I'm looking to achieve:

<ul class="sub-menu">
<li style="transition-delay: 0ms;></li>
<li style="transition-delay: 25ms;>
<ul class="sub-menu">
<li style="transition-delay: 0ms;>
<li style="transition-delay: 25ms;>
<li style="transition-delay: 50ms;>
</ul>
</li>
<li style="transition-delay: 50ms;></li>
<li style="transition-delay: 75ms;></li>
<li style="transition-delay: 100ms;></li>
</ul>


This is what my jQuery looks like:

$('ul.mobile-menu li.menu-item-has-children ul.sub-menu li').each(function(i){
$(this).css({ 'transition-delay': (i*25)+"ms" });
});


Any help would greatly be appreciated as I am just getting started with jQuery. I created a codepen so you can see the menu in action and visually see the issue.

http://codepen.io/creativenauts/pen/wGLqPg

Answer

Like this:

$('ul.mobile-menu li.menu-item-has-children ul.sub-menu').each(function(){
    $(this).children('li').each(function(i, li){ 
        $(li).css('transition-delay', (i*25)+'ms') 
    })
});
Comments