
- jQuery - Home
- jQuery - Roadmap
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
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.