Apply jQuery function to one element and *NOT* its descendants
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 ul
s beneath it. Is there a way to specify that I only want to include the elemen开发者_如何学Ct and not its descendants.
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');
});
精彩评论