jQuery closest() Method

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.

jQuery closest() Method

Syntax

The syntax of this method is given below:-

Syntax
$(selector).closest(selectorExpression, selectorElement)

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

Test it Live

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