Open In App

jQuery siblings() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The siblings() is an inbuilt method in jQuery that is used to find all siblings elements of the selected element. The siblings are those having the same parent element in DOM Tree. The DOM (Document Object Model) is a World Wide Web Consortium standard. This is defined for accessing elements in the DOM tree.

Syntax:

$(selector).siblings(function)

Here, the selector is the selected element whose siblings are going to be found.

Parameters: It accepts an optional parameter “function” which is going to say which siblings should be selected out of all the siblings.

Return Value: It returns all the siblings of the selected element.

jQuery code to show the working of siblings() function:

Example 1: In the below code, no parameter is passed to the siblings() function.

html




<!DOCTYPE html>
<html>
 
<head>
    <style>
        .sib * {
            display: block;
            border: 2px solid lightgray;
            color: black;
            padding: 5px;
            margin: 15px;
        }
    </style>
    <script src=
 
    </script>
    <script>
        $(document).ready(function () {
            $("h2").siblings().css({
                "color": "black",
                "border": "2px solid green"
            });
        });
    </script>
</head>
 
<body class="sib">
    <div>
        This is parent!!!
        <p>This is paragraph!!!</p>
        <span>This is span box!!!</span>
        <h2>This is heading 2!</h2>
        <h3>This is heading 3!</h3>
    </div>
</body>
 
</html>


Output: In the above code, all the siblings of “h2” get highlighted.

Example 2: In the below code, an optional parameter for the function is used to filter the search for siblings.

html




<!DOCTYPE html>
<html>
 
<head>
    <style>
        .sib * {
            display: block;
            border: 2px solid lightgrey;
            color: black;
            padding: 5px;
            margin: 15px;
        }
    </style>
    <script src=
 
    </script>
    <script>
        $(document).ready(function () {
            $("h2").siblings("span").css({
                "color": "black",
                "border": "2px solid green"
            });
        });
    </script>
</head>
 
<body class="sib">
    <div>
        This is parent element !
        <p>
            This is the first paragraph !!!
        </p>
        <span>
            first span box !!!
        </span>
        <h2>Heading 2!</h2>
        <span>
            second span box !!!
        </span>
        <h3>Heading 3!</h3>
        <span>
            third span box !!!
        </span>
        <p>
            This is the second paragraph !!!
        </p>
    </div>
</body>
 
</html>


Output: In the above code, all the siblings of “h2” with the element name “span” get selected.



Last Updated : 11 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads