jQuery Traversal - has() Method
Example
Check if an element is within another element:
$("ul").append("<li>" + ($("ul")..has("li").length ? "Yes" : "No") + "</li>"); $("ul").has("li").addClass("full");
Definition and Usage
The has() method reduces the set of matched elements to a subset that has descendants matching the specified selector or DOM element.
Syntax
.has(selector)
Parameter | Description |
---|---|
selector | String value, containing the selector expression that matches the elements. |
Detailed Explanation
If a jQuery object representing a collection of DOM elements is given, the .has() method constructs a new jQuery object using the subset of child elements that match the elements.
Think about the following page with nested lists:
<ul> <li>list item 1</li> <li>list item 2</li> <ul> <li>list item 2-a</li> <li>list item 2-b</li> </ul> </li> <li>list item 3</li> <li>list item 4</li> </ul>
We can apply this method to a collection of list items, like this:
$('li').has('ul').css('background-color', 'red');
The result of this call is that the background of item 2 is set to red, because this item is the only <li> that has a <ul> among the descendants.