jQuery Traversing Descendants


Traversing Down the DOM Tree

In logical relationships a descendant is a child, grandchild, great-grandchild, and so on.

jQuery provides the useful methods such as children() and find() that you can use to traverse down in the DOM tree either single or multiple levels to easily find or get the child or other descendants of an element in the hierarchy.

jQuery children() Method

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

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

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery children() Demo</title>
<style>
    .highlight{
        background: yellow;
    }        
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("ul").children().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 *