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


This returns the first ancestor of the selected HTML element.


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


  • 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">
  <meta charset="utf-8">
  <title>jQuery closest method</title>
  .tuts {
    margin: 10px;
    background: grey;
  li.lightcss {
    background: green;
 <script src=""></script> 
  <li class="tuts"><b>Click me!</b></li>
  <li class="tuts">You can also <b>Click me!</b></li>
$( document ).on( "click", function( event ) {
  $( ).closest( "li" ).toggleClass( "lightcss" );


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.

Spread the love

Be First to Comment

Leave a Reply

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