The jQuery has() method can be used to return single or multiple matching elements. It can be helpful to select the element that contains the matching items.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select and return the matching element inside it. You can use the element tag name, class name, or id to select. It is a required field. |
element | Specify the element to match and select. You can enter an expression or HTML element to match. It is a required field. |
jQuery has() Method to Return Single Element
If you want to select the single matching element, you have to use the method as given in the example below. The example specifies the single element as the argument of the jQuery has() method. After selecting the elements, it applies the CSS color to the elements.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("ul li").has("span").css("color","orange"); }); }); </script> <ul> <li>First Item</li> <li>Second <span>Item</span></li> <li>Third Item</li> <li>Last <span>Item</span></li> </ul> <button type="button" class="mybtn">Click to Select</button> |
Output
- First Item
- Second Item
- Third Item
- Last Item
You have to click the button given above to select the matching element. After selecting the element, it applies the orange color to the text of the elements.
Return Multiple Element Using the Method
The jQuery has() method can also be used to select multiple matching elements. To select the multiple matching elements, you have to use the method as given in the example below.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.mymultibtn').click(function(){ $("ul li").has("em, span, b").css("color","orange"); }); }); </script> <ul> <li><em>Welcome to Tutorialdeep!</em></li> <li>Learn jQuery from <span>Tutorialdeep</span>.</li> <li><b>Check live examples</b> to learn and use on your project.</li> <li>Leave a comment if you have any queries.</li> </ul> <button type="button" class="mymultibtn">Click to Select Multiple</button> |
Output
- Welcome to Tutorialdeep!
- Learn jQuery from Tutorialdeep.
- Check live examples to learn and use on your project.
- Leave a comment if you have any queries.
When you click the button given above, it selects the multiple matching elements. After selecting the elements, It applies orange color to the text of the multiple selected elements.
You may also like to read
I hope you like this tutorial on jQuery has() method. If you have any queries regarding the tutorial, please comment below.
References