JQuery Ancestors

 15 - Oct - 2021
 XpertPhp
 23

In jquery, there are three useful jquery methods for traversing up the DOM tree. such as parent(), parents() and parentsUntil().

jQuery parent() Method

The jQuery parent() method is used to get the parent element of the specified elements.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").parent().css("border","1px solid red"); 
  });
});
</script>
</head>
<body>
  <div class="box">
     <p>This is paragraph tag.</p>
   </div>
  <button>Click here</button>
</body>
</html>

jQuery parents() Method

The jQuery parents() method is used to get all the ancestor elements (up to the document root) of the specified elements.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#test").parents('div').css("background-color", "yellow");
  });
});
</script>
</head>
<body>
   <div>
        <p>This is paragraph tag 1</p>
        <div>
	     <p id="test">This is paragraph tag 2</p>
        </div>
        <p>This is paragraph tag 3</p>
    </div>
  <button>Click here</button>
</body>
</html>

jQuery parentsUntil() Method

The jQuery parentsUntil() method is used to return all ancestor elements between two given arguments.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$("button").click(function(){
		$(".child").parentsUntil('#subnav').css("background-color", "yellow");; 
	});
});
</script>
</head>
<body>
<div class="box">
       <ul class="nav">
        	<li>List 1</li>
        	<li>List 2
				<ul id="subnav">
                  <li> List 2.1
                    <ul>
                      <li class="child">List 2.1.1</li>
                    </ul>
                  </li>
                </ul>
			</li>
          	<li>List 3</li>
        	<li>List 4</li>
    	</ul>
   </div>
  <button>Click here</button>
</body>
</html>