Javascript examples for jQuery Method and Property:closest
The closest() method returns the first ancestor of the selected element.
$(selector).closest(filter,context);
Parameter | Require | Description |
---|---|---|
filter | Required. | selector expression, element or jQuery object to narrow down the ancestor search |
context | Optional. | A DOM element within which a matching element may be found |
The following code shows how to Return the first ancestor of <span>, that is an <ul> element:
<!DOCTYPE html> <html> <head> <style> .ancestors * {/*from w ww. j ava 2 s .c o m*/ display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("span").closest("span").css({"color": "red", "border": "2px solid red"}); }); </script> </head> <body class="ancestors">body <div style="width:500px;">div <ul>ul <li>li<span>span</span></li> </ul> </div> </body> </html>