jQuery API

.has()

.has( selector ) Returns: jQuery

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

  • version added: 1.4.has( selector )

    selectorA string containing a selector expression to match elements against.

  • version added: 1.4.has( contained )

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

Example:

Check if an element is inside another.

<!DOCTYPE html>
<html>
<head>
  <style>
  .full { border: 1px solid red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	
<ul><li>Does the UL contain an LI?</li></ul>

<script>
  $("ul").append("<li>" + ($("ul").has("li").length ? "Yes" : "No") + "</li>");
  $("ul").has("li").addClass("full");
</script>
</body>
</html>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .has() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.

2 Comments

  1. Posted February 3, 2010 at 1:21 pm | Permalink

    If you want to filter the selected elements by those which do NOT have descendants matching a selector, wrap your :has() in a :not() like so: $(“li:not(:has(p))”);

  2. rv4wd
    Posted February 24, 2010 at 8:30 am | Permalink

    This has() function differs slightly from the has selector:
    $('ul:has(>li)') works, $('ul').has('>li') does not work

Post a Comment

You must be logged in to post a comment.