开发者

Find element and add class (jQuery)

开发者 https://www.devze.com 2022-12-08 06:23 出处:网络
<ul> <li><a href=\"#\">LEVEL 1</a> <ul> <li>...</li> </ul>
<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");
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号