How to get the siblings of an element in jQuery

Filed Under: jQuery

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.


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

jquery-siblings-example

Comments

  1. Bhaskar says:

    Above given out put image second row, Mark and Steve are siblings of Tom. Need to highlight Tom, but highlighting the steve.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages