Jquery Traversing

Jquery Traversing

There are several jQuery methods that you can use for traversing the DOM tree, including:

  1. .parent() – Selects the parent element of the selected element.
  2. .children() – Selects all the child elements of the selected element.
  3. .siblings() – Selects all the sibling elements of the selected element.
  4. .find() – Selects all descendant elements of the selected element that match a specified selector.
  5. .next() – Selects the next sibling element of the selected element.
  6. .prev() – Selects the previous sibling element of the selected element.

Here’s an example of how you can use these methods:

 

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Traversing Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        ul {
            list-style-type: none;
            padding: 0;
        }
        li {
            padding: 5px;
            border: 1px solid black;
        }
        .active {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <h2>jQuery Traversing Example</h2>
    <ul>
        <li>Item 1</li>
        <li class="active">Item 2
            <ul>
                <li>Subitem 1</li>
                <li>Subitem 2</li>
            </ul>
        </li>
        <li>Item 3</li>
        <li>Item 4</li>
    </ul>
    <script>
        $(document).ready(function() {
            // Select the parent of the active list item
            $(".active").parent().css("background-color", "gray");

            // Select all the child elements of the active list item
            $(".active").children().addClass("active");

            // Select all the sibling elements of the active list item
            $(".active").siblings().css("border-color", "red");

            // Select all the descendant elements of the list that have the class "active"
            $("ul").find(".active").css("font-weight", "bold");

            // Select the next sibling element of the active list item
            $(".active").next().addClass("active");

            // Select the previous sibling element of the active list item
            $(".active").prev().addClass("active");
        });
    </script>
</body>
</html>
Scroll to Top