Normally, siblings are the elements that share the same parent. jQuery provides several methods such as siblings(), next(), nextAll(), nextUntil(), prev(), prevAll() and prevUntil() that can be used to traverse sideways in the DOM tree.
jQuery siblings() Method
Description
Siblings() method in jQuery is used to bring the sibling elements of the required element. The below example will impresses the siblings of the <p> element which are <h1> and <ul> by adding the class "highlight" on document ready.
[html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery siblings() Demo</title>
<style type="text/css">
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").siblings().addClass("highlight");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
[/html]
Output:
Multiple selectors can be included as parameters within the siblings() method to filter the search for the siblings.
next() Method
Description
The immediate next sibling i.e. the next sibling element of the selected element can be obtained using next() method. The following example will highlight the next sibling of the <p> element which is the <ul> element.
[html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery next() Demo</title>
<style type="text/css">
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").next().addClass("highlight");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
[/html]
Output:
The method nextAll() is used to get all following siblings of the selected element.
prev() Method
Description
The method prev() is used to get the immediately previous sibling of the selected element. The following example will highlight the previous sibling of the <ul> element which is the <p> element.
[html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery prev() Demo</title>
<style type="text/css">
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("ul").prev().addClass("highlight");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
[/html]
Output:
Summary
Key Points
Siblings are the elements that share the same parent.
Siblings elements brings siblings of the selected elements.