Find element and add class (jQuery)
<ul>
<li><a href="#">LEVEL 1</a>
<ul>
<li>...</li>
</ul>
</li>
<li><a href="#">LEVEL 1</a>
<ul>
<li>...</li>
</ul>
</li>
</ul>
开发者_运维百科I have a nested list and I want to use jQuery to add class to the LI that containts A>LEVEL 1
based on this condition: if a nested UL exists AFTER UL LI A, do x else y
.
Thanks.
To simply add a class to the <li>
elements that have an anchor followed by a <ul>
do this:
$("ul li:has(a + ul)").addClass("someClass");
If you really need different classes on whether it's true then you'll need some code:
$("ul li").each(function() {
var a = $(this).children("a");
if (a.next("ul").length > 0) {
$(this).addClass("first");
} else {
$(this).addClass("second");
}
});
精彩评论