jQuery Traversing - Ancestors

jQuery Traversing - Ancestors

To discover an element's ancestors, you may use jQuery to traverse up the DOM tree.

A parent, grandparent, great-grandparent, and so on are all examples of ancestors.

You can also search for these topics, traversing the all ancestors using jquery, execute the traversing ancestors dom using jquery, ancestors filter, traverse ancestors html and xml, how to use jquery traverse ancestors object and properties, jquery traversing ancestors next sibling, define the value of jquery traversing ancestors.

Traversing Up the DOM Tree

For Ancestors Traversing the DOM tree, there are three important jQuery methods :

  • parent() - Single level parent
  • parents() - Multilevel parent till root element.
  • parentsUntil() - Multilevel parent till a specified element.
You can also search for these topics, methods for traversing up the dom tree in jquery, html and xml, code to execute the jquery traversing up the dom tree, which of the following are methods for traversing up the dom tree, Types of Traversing Up the DOM Tree.

jQuery parent() Method

The direct parent of the chosen element is returned by the parent() function.

Only a single level of the DOM tree is traversed by this technique.

Example :- The example below retrieves the parent element of the h4:

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    $(document).ready(function () {
        $("#b1").click(function () {
            $("h4").parent().css({ "color": "red", "border": "2px solid blue" });
<div id="div1">div 1 - (great-grandparent)<br /><br />
    <div id="div2">div 2 - (grand-parent)<br /><br />
        <div id="div3">div 3 - (parent)<br /><br />
            <h4>i am h4</h4>
  </div><br />
  <button id="b1">Show Parent Of H4</button>

Output :-

div 1 - (great-grandparent)

div 2 - (grand-parent)

div 3 - (parent)

i am h4

You can also search for these topics, how to find parent method in jquery, get parent element from child using jquery, jquery extend and widget call parent method, child selector, parent and sibling method, xml and html, button click function to jquery parent method, example.

jQuery parents() Method

All ancestor elements of the chosen element are returned by the parents() function, up to and including the document's root element (html).

You can also search for these topics, how to find the jQuery parents(), jQuery parents() selector, jQuery parents with class, example for jQuery parents() method.

jQuery parentsUntil() Method

All ancestor items between two parameters are returned by the parentsUntil() function.

You can also search for these topics, search parent until execute the jquery parentsuntil method, filter element using to works the jquery parentsuntil method, how to find the jquery parentsuntil method, jquery to get all parentsuntil() method, method post and class jquery parentsuntil, example for jquery parentsuntil() method.