tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

has()

Returns: jQuery

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

.has( selector )

version added: 1.4
selector
A string containing a selector expression to match elements against.

.has( contained )

version added: 1.4
contained
A 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 simple list on it:

<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:
$('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.

  • list item 1
  • list item 2
    • list item 2-a
    • list item 2-b
  • list item 3
  • list item 4

Example

Check if an element is inside another.
$("ul").append("<li>" + ($("ul").has("li").length ? "Yes" : "No") + "");
$("ul").has("li").addClass("full");

The output of the code above will be:

Example - Full source:

Check if an element is inside another.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>

  <style>
  .full { border: 1px solid red; }
</style>

<script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" language="javascript">

  $(document).ready(function(){
$("ul").append("<li>" + ($("ul").has("li").length ? "Yes" : "No") + "");
$("ul").has("li").addClass("full");    
  });
  </script>

</head>
<body>
<ul><li>Does the UL contain an LI?</li></ul>

</body>
</html>
Was this information helpful?
   

Comments