jQuery closest() method can be used to return the first specified ancestor of the selected element. It finds the closest matching element which can be the first parent element.
To find the closest element, it starts from the selected element and traverse upward to get the specified element. If the element is matching with the element, it gives the result by selecting the matching element.
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 find its closest specified ancestor element. You can use the element tag name, class name, or id to select. It is a required field. |
selectorExpression | It is the selector expression that can be an element or jQuery object. It is a required field. |
selectorElement | Specify the DOM element within which the matching element may be present. It is an Optional field. |
jQuery closest() Method to Find the Ancestor
If you want to get the ancestor of the selected element, you have to use the method given below. The example contains a list of elements and the span element inside it. It finds the first ul element for the selected span element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("span").closest("ul").addClass("mybg"); }); }); </script> <style> .mybg{ background:#ccc; border:1px solid orange; } </style> <ul>Second ul ancestor. <li>First li item. <ul>First ul ancestor. <li> <span>Span element</span> </li> <li>This is list element</li> </ul> </li> <li>Second li item.</li> <li>Third li item.</li> </ul> <button type="button" class="mybtn">Click to Return Closest</button> |
Output
- Second ul ancestor.
- First li item.
- First ul ancestor.
- Span element
- This is list element
- Second li item.
- Third li item.
When you click the button given above, it selects the first ancestor element which the ul element. After selecting the element, it highlights it by adding the class to the element.
You may also like to read
I hope you like this tutorial on jQuery closest() method. If you have any queries regarding the tutorial, please comment below.
References