jQuery | siblings() with Examples
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.
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:

Recommended Posts:
- jQuery | Traversing Siblings
- jQuery | element ~ siblings Selector
- jQuery | has() with Examples
- jQuery | after() with Examples
- jQuery | one() with Examples
- jQuery | eq() with Examples
- jQuery | val() with Examples
- jQuery | last() with Examples
- jQuery | first() with Examples
- jQuery | on() with Examples
- jQuery | children() with Examples
- jQuery | change() with Examples
- jQuery | queue() with Examples
- jQuery | removeData() with Examples
- jQuery | offset() with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



