The jQuery is() method can be used to check whether the matching element is present or not. It finds one of the selected element if matches with the specified element.
You will get true if a matching element is present and false if the element is not present.
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 check if the matching element present. You can use the element tag name, class name, or id to select. It is a required field. |
selectorElement | Specify the selector element, expression, or jQuery object to match the current set of elements against. It returns true if the element is present and false if not. It is a required field. |
index | It returns the index position of the element. It is an optional field. |
element | Returns the current element you are using. It is the optional field. |
jQuery is() Method to Check Matching Parent Element
If you want to find the specified element is the parent of the selected element, you have to use the method as given below. The example contains the list items and find if the li element is the parent of the span element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ if($("span").parent().is("li")){ alert("The parent of 'span' is 'li'"); }; }); }); </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 Check</button> |
Output
- First Item
- Second
- Third Item
- Last
You have to click the button given above to find if the specified element is the parent. The above example showing the alert box that confirms that the specified element is the parent.
Check If Class is Present Using the Method
The jQuery is() method is also helpful when you want to check if the class is present. 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 15 16 17 18 |
<script> $(document).ready(function(){ $('ul li').click(function(){ if($(this).is(".second")){ alert("This is second list element.'"); }else{ alert("This is not second list element.'"); }; }); }); </script> <ul> <li class="first">1st element</li> <li class="second">2nd element</li> <li class="third">3rd element</li> <li class="forth">4th element</li> </ul> <p>Click the above list items to check</p> |
Output
- 1st element
- 2nd element
- 3rd element
- 4th element
Click the above list items to check
When you click each item of the list element, you will get an alert box that confirms that the specified class is present.
You may also like to read
I hope you like this tutorial on jQuery is() method. If you have any queries regarding the tutorial, please comment below.
References