How to find all the siblings for the clicked element in jQuery?

To find all the siblings for the clicked element in jQuery, use the siblings() method along with proper element selection. The siblings() method returns all sibling elements of the selected element, which are elements that share the same parent.

Understanding the siblings() Method

The siblings() method in jQuery selects all sibling elements of the matched element. When combined with click events, you can easily identify and manipulate all related elements in the same container.

Example

You can try to run the following code to find all the siblings for the clicked element in jQuery ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $(".target").click(function(){
                // Remove class from all siblings
                $(this).siblings().removeClass("selectedClass");
                // Add class to clicked element
                $(this).addClass("selectedClass");
            });
        });
    </script>
    <style>
        a {
            cursor: pointer;
            display: block;
            padding: 5px;
            margin: 2px 0;
        }
        .selectedClass {
            color: blue;
            font-weight: bold;
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <h1>Countries</h1>
    <ul>
        <li><a class="target">India</a></li>
        <li><a class="target">US</a></li>
        <li><a class="target">UK</a></li>
        <li><a class="target">Canada</a></li>
    </ul>
</body>
</html>

In this example, when you click on any country name, the siblings() method finds all other anchor elements at the same level and removes the selectedClass from them, while adding the class to the clicked element.

How It Works

The jQuery code uses the following approach ?

  • $(this).siblings() ? Selects all sibling elements of the clicked item
  • removeClass("selectedClass") ? Removes the highlight class from siblings
  • addClass("selectedClass") ? Adds the highlight class to the clicked element

Conclusion

The siblings() method in jQuery provides an efficient way to select and manipulate all sibling elements of a clicked element, making it useful for creating interactive lists and navigation menus.

Updated on: 2026-03-13T18:49:01+05:30

848 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements