Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
jQuery Traversing Siblings
With jQuery, you can easily find siblings of an element using the following methods: next(), nextAll(), prev(), prevAll(), siblings(), etc. Let us see some of them traverse siblings−
next() method
The next() method is used to return the next sibling element of the selected element. Let us see an example−
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
width:600px;
}
.demo * {
display: block;
border: 2px solid orange;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("h3").next().css({"color": "gray", "border": "3px dashed blue"});
});
</script>
</head>
<body class="demo">
<div> parent
<h1>sibling</h1>
<h2>sibling</h2>
<h3>sibling</h3>
<h4>sibling</h4>
</div>
</body>
</html>
Output
This will produce the following output−

prev() method
The prev() method is used to return the previous sibling element of the selected element. Let us see an example−
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
width:600px;
}
.demo * {
display: block;
border: 2px solid orange;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("h3").prev().css({"color": "gray", "border": "3px dashed blue"});
});
</script>
</head>
<body class="demo">
<div> parent
<h1>sibling</h1>
<h2>sibling</h2>
<h3>sibling</h3>
<h4>sibling</h4>
</div>
</body>
</html>
Output
This will produce the following output−

siblings() method
The siblings() method is used to return all sibling elements of the selected element. Let us see an example−
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
width:600px;
}
.demo * {
display: block;
border: 2px solid orange;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
<script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("h3").siblings().css({"color": "gray", "border": "3px dashed blue"});
});
</script>
</head>
<body class="demo">
<div> parent
<h1>sibling</h1>
<h2>sibling</h2>
<h3>sibling</h3>
<h4>sibling</h4>
</div>
</body>
</html>
Output
This will produce the following output−

Advertisements