jQuery Ancestors

In jQuery, ancestor traversal means moving upward in the DOM tree from a selected element to its parent, grandparent, great-grandparent, etc.


Traversing Up the DOM Tree

jQuery provides several methods to go up the DOM tree—from a specific element to its parents, grandparents, and so on.

Method

Description

.parent()

Selects the immediate parent

.parents()

Selects all ancestors

.parentsUntil()

Selects ancestors up to a selector (exclusive)

jQuery parent() Method


The .parent() method returns the immediate parent of the selected element.

It goes one level up the DOM tree and returns only one element per match.


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

Example
<script>
$(document).ready(function(){
$("span").parent().css({"color": "red", "border": "2px solid red"});
});
</script>

Try it yourself

jQuery parents() Method

The .parents() method gets all ancestor elements of the selected element, going all the way up the DOM tree until it reaches the <html> element.


The following example returns all ancestors of all <span> elements:

Example
<script>
$(document).ready(function(){
$("span").parents().css({"color": "red", "border": "2px solid red"});
});
</script>

Try it yourself

.parents() method — you can pass a selector as an optional parameter to filter the ancestors you want to target.


The following example returns all ancestors of all <span> elements that are <div> elements:

Example
<script>
$(document).ready(function(){
$("span").parents("div").css({"color": "red", "border": "2px solid red"});
});
</script>

Try it yourself

jQuery parentsUntil() Method


The .parentsUntil() method traverses up the DOM tree from the selected element and returns all ancestors up to (but not including) the element matched by the selector.


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

Example
<script>
$(document).ready(function(){
$("span").parentsUntil("div").css({"color": "red", "border": "2px solid red"});
});
</script>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.