• jQuery Video Tutorials

jQuery closest() Method



The closest() method in jQuery is used to traverse up the DOM tree to find the nearest ancestor of the selected elements that matches the specified selector.

The method moves up the DOM tree from the current element to find an ancestor that matches the selector. It returns the first element that matches the selector, starting from the current element itself and then moving up. The traversal continues up to the document root if no match is found.

Even if multiple elements match the selector, only the first one encountered is returned.

Syntax

Following is the syntax of jQuery traversal closest() −

$(selector).closest(filter)

Parameters

This method accepts the following parameters −

  • filter: This selects closest ancestor of each selected element that matches the specified selector.

Example 1

In the following example, we are demonstrating how to use closest() method to find the closest ancestor <div> element when clicking on a button within it −

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var closestDiv = $(this).closest("div");
        closestDiv.css("background-color", "lightblue");
    });
});
</script>
<style>
    div {
        border: 1px solid black;
        padding: 10px;
        margin: 10px;
    }
</style>
</head>

<body>
<div>
    <p>This is the third div element.</p>
  <div>
    <p>This is the second div element.</p>
    <div>
      <p>This is the first div.</p>
      <button>Click to highlight closest div</button>
    </div>
  </div>
</div>
</body>
</html>

After clicking the button inside the <div>, the closest ancestor <div> will be highlighted with lightblue background color.

jquery_ref_traversing.htm
Advertisements