jQuery | :has() Selector with example

The :has() selector in jQuery is used to select all elements that have one or more elements inside of them, that matches the specified selector.

Syntax:

$(":has(selector)")

Parameter: This selector contains single parameter selector which is mandatory and used to specify the element to select. It is also required to accept any kind of selector.



Example 1: This example uses :has selector to select <h2> span element to create solid green border.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
   <head>
      <title>jQuery :has() Selector</title>
        
      <script src=
      </script>
        
      <!-- Script to use :has selector -->
      <script>
         $(document).ready(function(){
           $("h2:has(span)").css("border", "solid green");
         });
      </script>
   </head>
     
   <body>
      <center>
         <h1 id="geeks1" style = "color:green;">GeeksForGeeks</h1>
         <h2 id="geeks2"><span>jQuery :has() Selector</span></h2>
      </center>
   </body>
</html>

chevron_right


Output:

Example 2: This example uses :has selector to select element and create border.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
   <head>
      <title>jQuery :has() Selector</title>
        
      <script src=
      </script>
        
      <!-- Script to use :has selector -->
      <script>
         $(document).ready(function(){
           $("body:has(h1, span)").css("border", "solid green");
         });
      </script>
   </head>
     
   <body>
      <center>
         <h1 id="geeks1" style = "color:green;">GeeksForGeeks</h1>
         <h2 id="geeks2"><span>jQuery :has() Selector</span></h2>
      </center>
   </body>
</html>

chevron_right


Output:



My Personal Notes arrow_drop_up

Small things always make you to think big

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.