jQuery Get/Find Closets Element

jQuery find closest element; Through this tutorial, i am going to show you how to get or find the first ancestor or closets element of selected HTML using jQuery closets() method.

jQuery Get Closets Element

You can use jQuery closets method to get/find closest element by class, id and tag:

  • jQuery closest() Method
  • Syntax jQuery closest() Method
  • Parameters of jQuery closest() Method
  • Example of jquery find closest element

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 jQuery 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 of jQuery closest() Method

  • 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.

Example of jquery find closest element

See the following example for how use jquery closest method to find closest element selected html elements; as shown below:

<!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>

Demo for how to find closest element in jquery

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

Recommended jQuery Tutorials

Be First to Comment

Leave a Reply

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