Alfero Chingono
Alfero Chingono

Reputation: 2663

jQuery: determine if a <li> contains a <ul>

I have some HTML code that contains nested <ul> elements and I need to add a class 'parent' to each <li> element that contains a child <ul>. There could be more than one element contained directly withing a single <li>, e.g:

<li>
    <a>...</a>
    <span>...</span>
    <ul>...</ul>
</li>

All I need is to determine if a particular <li> contains a <ul> as a child element.

How would I go about this?

Upvotes: 5

Views: 10004

Answers (3)

bryanbcook
bryanbcook

Reputation: 18393

Use the has selector.

$("li:has(ul)").addClass("parent")

Upvotes: 4

dcharles
dcharles

Reputation: 4852

This will accomplish what you need:

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

Upvotes: 28

MiffTheFox
MiffTheFox

Reputation: 21575

Changed the answer after re-reading the question:

$("li:has(ul)").addClass("parent");

Upvotes: 4

Related Questions