jQuery API

:has() Selector

has selector

version added: 1.1.4jQuery(':has(selector)')

  • selector
    Any selector.

Description: Selects elements which contain at least one element that matches the specified selector.

The expression $('div:has(p)') matches a <div> if a <p> exists anywhere among its descendants, not just as a direct child.

Additional Notes:

  • Because :has() is a jQuery extension and not part of the CSS specification, queries using :has() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").has(selector/DOMElement) instead.

Example:

Adds the class "test" to all divs that have a paragraph inside of them.

<!DOCTYPE html>
<html>
<head>
  <style>
  .test{ border: 3px inset red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div><p>Hello in a paragraph</p></div>

  <div>Hello again! (with no paragraph)</div>
<script>$("div:has(p)").addClass("test");</script>

</body>
</html>

Demo:

Support and Contributions

Need help with :has() Selector or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to :has() Selector? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://twitter.com/PGrandstaff Peter Grandstaff

    If you're looking for a selector for “Doesn't Have,” try:

    :not(:has(selector))

  • therealmonkeboy

    E.g:

    $('div:not(:has(h3))').css('color','red');

    alters all divs that don't have a H3

  • Jonathan Thérien

    I want to select all the table with more than 10 rows
    but this doesnt seem to work

    $('table:has(tr:gt(10))').length;

    $('table:has(tr:gt(10))').each(function(){
    //do stuff to the table with more than 10 row
    });

  • Miklos Martin

    And what should I do, if I want to select the parent of the element matching the selector?
    In an each loop I want to read an attribute of the current element's parent, and :has(this) is'nt working. 'li:has('+this+')' neither.
    Thanks for help!

  • Besuhoff

    try $(this).closest('selector')

  • Besuhoff

    try $(this).closest('selector')

  • Zworld005

    how come this doesn't work $(':has(selector)', e) as oppose to this e.has(selector).