Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

jQuery

Learn step by step



jQuery Traversing-Ancestors

Ancestor: It is a parent, grandparent & so on.

From jQuery we can traverse up the DOM tree to find ancestors of an element.

Traversing Up the DOM Tree

3 useful jQuery methods for traversing up the DOM tree are:

  • parent()
  • parents()
  • parentsUntil()
jQuery parent() Method

Function parent() returns the direct parent element of the selected element.

Function only traverse a single level up the DOM tree.

The below given example returns the direct parent element of each <span> elements:


<!DOCTYPE html>
<html><head>
<style>
.ancestors *
{
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parent().css({"color":"blue","border":"2px solid blue"});
});
</script>
</head>
<body>
<div class="ancestors">
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent)
<li>li (direct parent)
<span>span</span>
</li>
</ul>
</div>
<div style="width:500px;">div (grandparent)
<p>p (direct parent)
<span>span</span>
</p>
</div>
</div>
</body></html>

Output

jQuery parentsUntil() Method

Function parentsUntil() returns all the ancestor elements between two given arguments.

The below given example returns all ancestor elements between a <span> and a <div> element:


<!DOCTYPE html>
<html>
<head>
<style>
.ancestors *
{
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parentsUntil("div").css({"color":"red","border":"2px solid red"});
});
</script>
</head>
<body class="ancestors"> body (great-great-grandparent)
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent)
<li>li (direct parent)
<span>span</span>
</li>
</ul>
</div>
</body>
</html>

Output



Related Videos