tags:

views:

64

answers:

1

I want to add certain classes to the various levels of my websites nav header. So I'll have something in the end like

$('#navCol > ul > li > ul > li > ul').addClass('lvl2');
    // Each ‘li > ul’ past the first ‘ul’ indicates another sub-level.

to add the lvl2 class to the second level, etc. Having said that, not only does it apply said class to the second level, it also adds it to the other uls beneath it. Is there a way to specify that I only want to include the element and not its descendants.

+3  A: 

Try something like

$('#navCol > ul > li > ul > li').children("ul").each(function() {
    $(this).addClass('lvl2');
});

or if you just want the first url, try something like

$('#navCol > ul > li > ul > li').children("ul:first").each(function() {
    $(this).addClass('lvl2');
});
Chris Gutierrez
I think the `.each` is unnecessary. You can shorten the statement to just used `.addClass` following the `children("ul")` or `children("ul:first")` calls.
Doug Neiner
Oh! I realized what I did wrong. What I said in the question is valid and works. I was using a `for` loop to loop through adding ` li > ul` multiple times to `#navCol > ul`, but I forgot the extra `>` before the `li`, so that's why it didn't work. Chris' answer works, too, but the code I included in the question is valid and behaves correctly.
Alexsander Akers
I think you are right. I think jQuery will automatically iterate when it finds multiple elements. Good Call!
Chris Gutierrez