parents() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:parents

Description

The parents() method returns all ancestor elements of the selected element, including parent, grandparent, great-grandparent, and so on.

Syntax

Parameter RequireDescription
filterOptional. selector expression to narrow down the search for ancestors

To return multiple ancestors, separate each expression with a comma.

The following code shows how to get all parents for span until ul.

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * {//from   ww w.  j av  a 2  s  .c  om
    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").parents("ul").css({"color": "red", "border": "2px solid red"});
});
</script>
</head>

<body class="ancestors">body (great-great-grandparent)
  <div style="width:500px;">div
    <ul>ul
      <li>li (direct parent)
        <span>span</span>
      </li>
    </ul>
  </div>
</body>

</html>

Related Tutorials