How to get the first ancestor of an element in jQuery

Filed Under: jQuery

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.


<!doctype html>
<html>
<head>
<title>jQuery Traversing closest</title>
<style>
div,span{
      display: block;
      border: 3px solid lightgrey;
      color: black;
      padding: 5px;
      margin: 25px;
      width:300px;

}
span.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
</head>
<body>
<div>
  <span><b>Click me!</b></span>
  <span><b>Click me!</b></span>
  <span>You can also <b>Click me!</b></span>
</div>
<script>
$( document ).on( "click", function( event ) {
$( event.target ).closest( "span" ).toggleClass( "highlight" );
});
</script>
</body>
</html>

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages