开发者

How to add a class to list where there is unordered list child with jquery?

I would like to add a class called "with_ul" to li tags where there is ul under in the following normal list with jquery.

In the following case I need to add the class to list of Level 1-B, Level 2-B-1 and Level 1-C since they have an unordered list.

   <ul id="nav">
      <li>Level 1-A</li>
      <li>Lev开发者_运维知识库el 1-B
          <ul>
              <li>Level 2-B-1
                  <ul>
                      <li>Level 3-B-1</li>
              </li>
              <li>Level 2-B-2</li>
          </ul>
      </li>
      <li>Level 1-C
          <ul>
              <li>Level 2-C-1</li>
          </ul>
      </li>
...
...
</ul>

Thanks in advance.


$("li ul").parent().addClass('with_ul')


You can use the :has() selector to select all elements that contains a specific descendant.
For example:

$('li:has(ul)').addClass('with_ul');

If you only want to select <li> tags that directly contain a <ul>, you could write

$('li:has(li>ul)').addClass('with_ul');


Answer from Aaron is working ok, i would only modify it slightly, since sub items inherit style from parents, and everything under Level-1B would look the same, would be nice to add .no_url class:

$("ul#nav li").addClass("no_ul");
$("ul#nav li>ul").parent().removeClass("no_ul").addClass("with_ul");

EDIT: Slaks is even better ;)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜