Find element and add class (jQuery)

穿精又带淫゛_ 提交于 2019-12-23 04:30:13

问题


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


回答1:


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");
  }
});


来源:https://stackoverflow.com/questions/1565816/find-element-and-add-class-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!