closest() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:closest

Description

The closest() method returns the first ancestor of the selected element.

Syntax

$(selector).closest(filter,context);
Parameter Require Description
filterRequired.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:

Demo Code

ResultView the demo in separate window

<!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>

Related Tutorials