jquery
  1. jquery-closest

JQuery closest()

The jQuery closest() method is used to return the first ancestor element that matches a specified selector. It can be very useful when you need to traverse up the DOM tree to find elements or when you want to perform an action on a specific ancestor element.

Syntax

$(selector).closest(filter);
  • selector - Specifies the element to search for.
  • filter - Optional. Specifies a Boolean expression, a function, or a jQuery object that filters the search.

Use

The closest() method is usually used when you need to perform an action on a specific ancestor element. For example, you could use it to find the nearest parent div element with a specific class and change its background color.

Example

Here is an example that demonstrates how to use the closest() method:

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $(this).closest("div").css("background-color", "yellow");
      });
    });
  </script>
</head>
<body>

<div>
  <h2>jQuery closest() Method Example</h2>
  <p>This is a paragraph.</p>
  <button>Click me</button>
</div>

</body>
</html>
Try Playground

In this example, we have a div element that contains a h2, p and button element. When the button is clicked, the closest ancestor div element is located and its background color is changed to yellow.

Summary

The closest() method allows you to traverse up the DOM tree, looking for the nearest ancestor element that matches a specified selector. This method is useful when you need to locate a specific ancestor element in order to perform an action on it or to extract information from it.

Published on: