jQuery Traversing Ancestors

jQueryWeb DevelopmentFront End Technology

To traverse and find ancestors of an element, jQuery has the following methods: parent(), parents() and parentsUntil()−

parent() method

The parent() method in jQuery is used to return the direct parent element of the selected element. Let us see an example −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   width:600px;
}
.demo * {
   display: block;
   border: 2px solid yellow;
   color: blue;
   padding: 10px;
   margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("span").parent().css({"color": "blue", "border": "3px dashed blue"});
   });
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>

Output

This will produce the following output −

parents() method

The parents() method in jQuery is used to return all ancestor elements (till document root) of the selected element. Let us see an example −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   width:600px;
}
.demo * {
   display: block;
   border: 2px solid yellow;
   color: blue;
   padding: 10px;
   margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("span").parents().css({"color": "blue", "border": "3px dashed blue"});
   });
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>

Output

This will produce the following output −

parentsUntil() method

The parentsUntil() method in jQuery is used to return all ancestor elements between the selector and stop parameter value.

Example

Let us now see an example to implement the jQuery parentsUntil() method −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
div {
   width:600px;
}
.demo * {
   display: block;
   border: 2px solid yellow;
   color: blue;
   padding: 10px;
   margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("span").parentsUntil("div").css({"color": "blue", "border": "3px dashed blue"});
   });
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>

Output

This will produce the following output −

raja
Published on 31-Dec-2019 09:21:02
Advertisements