Return the first ancestor of <span>, that is an <ul> element:
In this example, $("span").closest("ul") searches for the first ancestor of span that is an ul element.
The closest ancestor of span is li, jQuery skips the li element and continue the search for the next ancestor until it locates ul.
If we use the parents()
method instead, it will return both ul ancestors.
<!DOCTYPE html> <html> <head> <style> .ancestors * {//from ww w .j a va 2 s . co m display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("span").closest("ul").css({"color": "red", "border": "2px solid red"}); }); </script> </head> <body class="ancestors">body <div style="width:500px;">div <ul>ul <ul>ul <li>li <span>span</span> </li> </ul> </ul> </div> </body> </html>
The closest()
method returns the first ancestor of the selected element.
Return the first ancestor of the selected element:
$(selector).closest(filter)
Return the first ancestor using a DOM context to look up the DOM tree within:
$(selector).closest(filter,context)
Parameter | Optional | Description |
---|---|---|
filter | Required. | a selector expression, element or jQuery object to search for the ancestor |
context | Optional. | A DOM element where a matching element may be found |