JQuery closest()
The jQuery closest()
method is used to return the first ancestor element that matches a specified selector. It can be very useful when you need to traverse up the DOM tree to find elements or when you want to perform an action on a specific ancestor element.
Syntax
$(selector).closest(filter);
selector
- Specifies the element to search for.filter
- Optional. Specifies a Boolean expression, a function, or a jQuery object that filters the search.
Use
The closest()
method is usually used when you need to perform an action on a specific ancestor element. For example, you could use it to find the nearest parent div
element with a specific class and change its background color.
Example
Here is an example that demonstrates how to use the closest()
method: