shin
shin

Reputation: 32721

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

Upvotes: 1

Views: 345

Answers (3)

SLaks
SLaks

Reputation: 887449

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');

Upvotes: 2

cichy
cichy

Reputation: 10644

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

Upvotes: 0

Aaron Saunders
Aaron Saunders

Reputation: 33345

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

Upvotes: 3

Related Questions