In this post, we will discuss how to get the siblings of an HTML element in jQuery. jQuery API provides siblings()
method to achieve this functionality.
jQuery siblings()
The siblings() method is used to return all the siblings of the selected HTML element. Unlike jQuery next()
and prev()
methods, this method traverses both forward and backwards along the siblings of the selected element. This method is very handy when you want to carry out similar tasks on a set of elements.
Here is the general syntax for using siblings method:
- selector.siblings( [filter ] )
filter is an optional parameter passed to the method to narrow down the traversal.
jQuery siblings() example
Following example demonstrates the jQuery siblings() usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!doctype html> <html> <head> <title>jQuery Traversing siblings</title> <style> span{ color: blue; margin: 30px; font-size: 16px; padding: 5px; font-weight: bolder; border: 1px solid lightgrey; } .highlight{ background: yellow; } div{ display: block; border: 3px solid lightgrey; color: lightgrey; padding: 5px; margin: 25px; width:350px; } </style> <script src="https://code.jquery.com/jquery-2.1.1.js"></script> </head> <body> <div> <span> Bheem</span> <span class="highlight"> Arjun</span> <span> Nakul</span> </div> <div> <span> Mark</span> <span class="highlight"> Tom </span> <span> Steve</span> </div> <div> <span> Sachin</span> <span> Saurav</span> <span> Zaheer </span> </div> <script> $( ".highlight" ).siblings() .css( "color", "red" ); </script> </body> </html> |
In this example, you can see three div
elements and each div
has three span
elements. In the first and second div
elements, the second span has a CSS style class “highlight”. The siblings() method returns all the siblings of the selected element having class=”highlight” and changes the color of the siblings to red.
In the firstdiv
, Bheem and Nakul are siblings of Arjun and in the second div
, Mark and Steve are siblings of Tom. This is how we get the siblings of an element in jQuery. Below image is the output produced by the above HTML page.