How to Find First Ancestor Using jQuery Closest

How to Find First Ancestor Using jQuery Closest

How to get or find the first ancestor of selected HTML elements. In this jquery tutorial, You will learn about the closest method and it’s uses. You can use the method for get or find the first ancestor of selected html elements.

In this jquery tutorial you will learn this method and uses of the method. So let’s see below of the method syntax, parameters and example

jQuery closest() Method

The closest () method of jQuery gives the first ancestor of the selected HTML element.

The closest method of JQuery accepts a mandatory parameter, which is used to filters the traversal. This method is starts traversal by find at the current element, it will return the current html element if it matches the specified expression, it will expand the DOM tree unless it detects an element that matches the filter.

Syntax closest() Method

$("selector").closest(first)

This returns the first ancestor of the selected HTML element.

$(selector).closest(first,second)

It returns the first ancestor using the DOM reference to use the DOM tree.

Parameters

  • First :- It is required. A selector specifies expression, element, or jquery object to reduce the search of ancestors.
  • Second :- It is optional. A DOM element within which a matching element may be found.

jQuery closest() method By Example

This example will demostrate you how use closest method to selected html elements.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery closest method</title>
  <style>
  .tuts {
    margin: 10px;
    background: grey;
  }
  li.lightcss {
    background: green;
  }
  </style>
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
</head>
<body>
 
<ul>
  <li class="tuts"><b>Click me!</b></li>
  <li class="tuts">You can also <b>Click me!</b></li>
</ul>
 
<script>
$( document ).on( "click", function( event ) {
  $( event.target ).closest( "li" ).toggleClass( "lightcss" );
});
</script>
 
</body>
</html>

Output

jQuery closest method
  • Click me!
  • You can also Click me!

In the above example of the closest () method, you will click on the elements and the background color of this element will change. We also use the jquery toggleClass () method along this method.

Leave a Reply

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