views:

343

answers:

1
<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.

+3  A: 

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");
  }
});
cletus
Ah, I just figured it out: $(".accordion ul li:has(ul)").addClass("CLASSY") but yours still better, thanks!
Nimbuz