jQuery Traversing Ancestors


Traversing Up the DOM Tree

In logical relationships an ancestor is a parent, grandparent, great-grandparent, and so on.

jQuery provides the useful methods such as parent()parents() and parentsUntil() that you can use to traverse up in the DOM tree either single or multiple levels to easily get the parent or other ancestors of an element in the hierarchy.

jQuery parent() Method

The jQuery parent() method is used to get the direct parent of the selected element.

The following example will highlight the direct parent element of the <li> which is <ul> by adding the class .highlight on document ready.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery parent() Demo</title>
<style>
    .highlight{
        background: yellow;
    }        
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("li").parent().addClass("highlight");
});
</script>
</head>
<body>
    <div class="container">
        <h1>Hello World</h1>
        <p>This is a <em>simple paragraph</em>.</p>
        <ul>
            <li>Item One</li>
            <li>Item Two</li>
        </ul>
    </div>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *