How to get the first ancestor of an element in jQuery With Example

In this post, we will discuss about the traversal method to get the first ancestor of the selected HTML element. jQuery API provides closest() method to perform this task.

jQuery closest()

The jQuery closest() method returns the first matched ancestor element of the selected HTML element. The method accepts a mandatory parameter, which filters out the traversal. This method starts traversal by first looking at the current element, it will return the current element if it matches the specified expression else it will traverse up the DOM tree until it found an element which matches the filter. This method will not return anything if the search does not found any matching element.

Here is the general syntax for using closest() method:

  • selector.closest(filter)
  • selector.closest(filter,context)

filter is a mandatory parameter passed to this method which filter out the ancestor search.

context is an optional parameter, which is a DOM element. A matching element may be found within this context.

jQuery closest() function example

Following example demonstrates the jQuery closet() method usage.

In this example, there are three span elements within the div element. The closest() method triggers when you click on the span elements. The filter passed here is “span” and it will first check the current element is a span. Since we click on the span element, the method will return that element and we carry out the desired actions. Here we use jQuery toggleClass to toggle between the CSS style class to change the background color.

This method will traverse up the DOM tree if the matching element is not found. You can try it out by clicking in any of the boxes below.

That’s all for now. we will look into more jQuery traversing methods in coming posts.

By admin

Leave a Reply

%d bloggers like this: