.has()

Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

.has(selector)🡢 jQuery

selector StringA string containing a selector expression to match elements against.

.has(contained)🡢 jQuery

contained ElementA DOM element to match elements against.

Given a jQuery object that represents a set of DOM elements, the .has() method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against the descendants of the matching elements; the element will be included in the result if any of its descendant elements matches the selector.

Consider a page with a nested list as follows:

<ul>
  <li>list item 1</li>
  <li>
    list item 2
    <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 the set of list items as follows:

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

The result of this call is a red background for item 2, as it is the only <li> that has a <ul> among its descendants.

Check if an element is inside another.

JS
<ul>
  <li>Does the UL contain an LI?</li>
</ul>
CSS
.full {
  border: 1px solid red;
}
HTML
$("ul").append("<li>" + ($("ul").has("li").length ? "Yes" : "No") + "</li>");
$("ul").has("li").addClass("full");
DEMO

Looking for a Web Developer?

👋

Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)