Traversing sibling elements with jQuery
In this article, we will discuss various jQuery methods to select siblings of an html element.
jQuery sibling methods
We can use following methods to select siblings of an element :
– prev()
– next()
– siblings()
Let’s use the following html for these examples :
<div>
<h2>H2</h2>
<h3>H3</h3>
<h4>H4</h4>
</div>

prev() and next() methods
The prev() jQuery method finds the immediate previous sibling of an element.
Similarly, the next() jQuery method finds the immediate next sibling of an element.
Example :
$('div').next()
$('div').prev()
Example program : Selecting previous and next sibling using prev() and next() methods
<!DOCTYPE html> <html> <head> <style> .block { display: block; border: 1px solid black; padding: 10px; color: black; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function() { $("h3").prev().css({ "color": "red", "border": "3px solid red" }); $("h3").next().css({ "color": "green", "border": "3px solid green" }); }); </script> </head> <body> <div class="block"> <h2 class="block">H2</h2> <h3 class="block">H3</h3> <h4 class="block">H4</h4> </div> </body> </html>
siblings() method
The siblings() method selects all the siblings of an elements.
Example :
$('div'.siblings()
Example program : Getting all siblings using siblings() method
<!DOCTYPE html> <html> <head> <style> .block { display: block; border: 1px solid black; padding: 10px; color: black; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function() { $("h3").siblings().css({ "color": "red", "border": "3px solid red" }); }); </script> </head> <body> <div class="block"> <h2 class="block">H2</h2> <h3 class="block">H3</h3> <h4 class="block">H4</h4> </div> </body> </html>
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post