Categories

:has() Selector

Categories: jQuery Extensions | Content Filter

jQuery(':has(selector)')

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

  • jQuery(':has(selector)')

    version added: 1.0

    selector   Any selector.

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

Note:

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.
  • Adds the class "test" to all divs that have a paragraph inside of them.

    HTML:
    <div><p>Hello in a paragraph</p></div>
    
      <div>Hello again! (with no paragraph)</div>
    CSS:
    
      .test{ border: 3px inset red; }
      
    Code:
    $("div:has(p)").addClass("test");