How does Traversing Ancestors works in Jquery?

In this blog, I will show you How Traversing Ancestors works in Jquery?

  • parent(): It is used to return the direct parent element of the given selected element.
  • parents(): It is used to return all the ancestor elements of the given selected element up to the parent element.
  • until parent(): It is used to return all the ancestor elements between the two given arguments.

jQuery parent() Method

For Example:

<!DOCTYPE html>
<html>
<head>
<style>
.demo* { 
  display: block;
  border: 3px solid red;
  color: blue;
  padding: 12px;
  margin: 12px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("span").parent().css({"color": "red", "border": "3px solid yellow"});
});
</script>
</head>
<body>

<div class="demo">
  <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>

jQuery parents() Method

For Example:

<!DOCTYPE html>
<html>
<head>
<style>
.demo* { 
  display: block;
  border: 3px solid blue;
  color: red;
  padding: 12px;
  margin: 12px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("span").parents().css({"color": "red", "border": "3px solid yellow"});
});
</script>
</head>

<body class="demo">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>

jQuery parentsUntil() Method

For Example:

<!DOCTYPE html>
<html>
<head>
<style>
.demo * { 
  display: block;
  border: 2px solid red;
  color: blue;
  padding: 11px;
  margin: 12px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("span").parentsUntil("div").css({"color": "red", "border": "2px solid yellow"});
});
</script>
</head>

<body class="demo"> 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>

Hope this blog is helpful for you ,Thanks for reading this blog.

dexpoundsofttechsolution

How does Traversing Ancestors works in Jquery?

s