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

 Live Demo

<!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

 Live Demo

<!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

 Live Demo

<!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−

Updated on: 30-Dec-2019

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements