Skip to content
Related Articles

Related Articles

jQuery | siblings() with Examples
  • Last Updated : 13 Feb, 2019

The siblings() is an inbuilt method in jQuery which is used to find all siblings elements of the selected element. The siblings are those having same parent element in DOM Tree. The DOM (Document Object Model) is a World Wide Web Consortium standard. This is defines 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 are going to say that 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:

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




<html>
  
<head>
    <style>
        .sib * {
            display: block;
            border: 2px solid lightgray;
            color: black;
            padding: 5px;
            margin: 15px;
        }
    </style>
                  jquery/3.3.1/jquery.min.js"></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>


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

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




<html>
  
<head>
    <style>
        .sib * {
            display: block;
            border: 2px solid lightgrey;
            color: black;
            padding: 5px;
            margin: 15px;
        }
    </style>
                  jquery/3.3.1/jquery.min.js"></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>


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

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :