jQuery closest()
The jQuery closest() method returns the first matched ancestor element of the selected HTML element. The method accepts a mandatory parameter, which filters out the traversal. This method starts traversal by first looking at the current element, it will return the current element if it matches the specified expression else it will traverse up the DOM tree until it found an element which matches the filter. This method will not return anything if the search does not found any matching element.
Here is the general syntax for using closest() method:
- selector.closest(filter)
- selector.closest(filter,context)
filter is a mandatory parameter passed to this method which filter out the ancestor search.
context is an optional parameter, which is a DOM element. A matching element may be found within this context.
jQuery closest() function example
Following example demonstrates the jQuery closet() method usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<!doctype html> <html> <head> <title>jQuery Traversing closest</title> <style> div,span{ display: block; border: 3px solid lightgrey; color: black; padding: 5px; margin: 25px; width:300px; } span.highlight { background: yellow; } </style> <script src="https://code.jquery.com/jquery-2.1.1.js"></script> </head> <body> <div> <span><b>Click me!</b></span> <span><b>Click me!</b></span> <span>You can also <b>Click me!</b></span> </div> <script> $( document ).on( "click", function( event ) { $( event.target ).closest( "span" ).toggleClass( "highlight" ); }); </script> </body> </html> |
In this example, there are three span elements within the div element. The closest() method triggers when you click on the span elements. The filter passed here is “span” and it will first check the current element is a span. Since we click on the span element, the method will return that element and we carry out the desired actions. Here we use jQuery toggleClass to toggle between the CSS style class to change the background color.
This method will traverse up the DOM tree if the matching element is not found. You can try it out by clicking in any of the boxes below.
That’s all for now. we will look into more jQuery traversing methods in coming posts.