The jQuery has following methods for traversing up the DOM tree:
jQuery parent() Method
The jQuery parent() method is used to get the direct single parent element of the selected element.
Example of Code
<style>
.jquery-example-ancestors-parent * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".jquery-example-ancestors-span-parent").parent().css({"color": "black", "border": "4px solid black"});
});
</script>
<div class="jquery-example-ancestors-parent">
<ul>ul (grandparent)
<li>li (direct parent)
<span class="jquery-example-ancestors-span-parent">span</span>
</li>
</ul>
</div>
Output
ul (grandparent)- li (direct parent)span
jQuery closest() method
The closest() method is used to get the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on.
Example of Code
<style>
.jquery-example-ancestors-closest * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".jquery-example-ancestors-span-closest").closest(".jquery-example-ancestors-ul-closest").css({"color": "black", "border": "4px solid black"});
});
</script>
<div class="jquery-example-ancestors-closest">
<ul class="jquery-example-ancestors-ul-closest">ul (grandparent)
<li>li (direct parent)
<span class="jquery-example-ancestors-span-closest">span</span>
</li>
</ul>
</div>
Output
ul (grandparent)- li (direct parent)span
The parentsUntil() method is used to get all ancestor elements between two given arguments.
Example of Code
<style>
.jquery-example-ancestors-parentsUntil * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".jquery-example-ancestors-span-parentsUntil").parentsUntil(".jquery-example-ancestors-ul-parentsUntil").css({"color": "black", "border": "4px solid black"});
});
</script>
<div class="jquery-example-ancestors-parentsUntil">
<ul class="jquery-example-ancestors-ul-parentsUntil">ul (grandparent)
<li>li (direct parent)
<span class="jquery-example-ancestors-span-parentsUntil">span</span>
</li>
</ul>
</div>
Output
ul (grandparent)- li (direct parent)span
