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

Try it yourself

Definition and Usage

The has() method reduces the set of matching element collections 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 matching elements. The selector used is to detect the descendants of the matching elements; if any descendant element matches the selector, the element will be included in the result.

Please 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 set of list items like this:

$('li').has('ul').css('background-color', 'red');

Try it yourself

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.