How to get/set elements containing the closest parent element matches the specified selector using jQuery ?
In this article, we will learn how to get a set of elements containing the closest parent element that matches the specified selector, the starting element included using jQuery.
Approach: We will use the closest() method of jQuery for this purpose. This method is used for accessing the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
.closest( selector, context )
Parameters: It has the following parameters as mentioned above and described below.
- selector: This specifies the element to be searched in the DOM tree. This can be a selector or a reference to the element.
- context: This is an optional parameter within which the matching element is to be found.
The below examples will demonstrate the above approach.