jQuery Siblings

jQuery provides methods to traverse sibling elements in the DOM tree. These methods include siblings(), next(), and prev(). They allow you to dynamically interact with elements that share the same parent.

Key Topics

Using siblings()

The siblings() method retrieves all siblings of the selected element.

$("#current").siblings();

Explanation: This code retrieves all sibling elements of the element with the ID current.

Using next() and prev()

The next() method retrieves the next sibling, while prev() retrieves the previous sibling.

// Get the next sibling
$("#current").next();

// Get the previous sibling
$("#current").prev();

Explanation: These methods navigate to adjacent siblings of the selected element.

Example: Traversing Siblings


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Siblings Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <ul>
        <li id="item1">Item 1</li>
        <li id="item2">Item 2</li>
        <li id="item3">Item 3</li>
    </ul>
    <button id="getSiblingsButton">Get Siblings</button>
    <button id="getNextButton">Get Next</button>
    <button id="getPrevButton">Get Previous</button>

    <script>
        $(document).ready(function() {
            $("#getSiblingsButton").click(function() {
                let siblings = $("#item2").siblings().map(function() {
                    return $(this).text();
                }).get();
                alert("Siblings: " + siblings.join(", "));
            });

            $("#getNextButton").click(function() {
                let next = $("#item2").next().text();
                alert("Next Sibling: " + next);
            });

            $("#getPrevButton").click(function() {
                let prev = $("#item2").prev().text();
                alert("Previous Sibling: " + prev);
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates how to retrieve all siblings, the next sibling, and the previous sibling of a selected list item using buttons.

Key Takeaways

  • All Siblings: Use siblings() to retrieve all siblings of an element.
  • Adjacent Siblings: Use next() and prev() for navigating to adjacent siblings.
  • Dynamic Interaction: Sibling methods are ideal for creating interactive menus and layouts.