jQuery siblings() Method



The siblings() method in jQuery is used to select all the sibling elements of the selected element(s). A sibling is an element that shares the same parent with another element. This method allows you to traverse both forward and backward among the sibling elements of DOM elements.

Syntax

Following is the syntax of siblings() method in jQuery −

$(selector).siblings(filter)

Parameters

This method accepts the following optional parameter −

  • filter: A string containing a selector expression to filter the sibling elements.

Example 1

In the following example, we are demonstrating the basic usage of siblings() method in jQuery −

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
        $("li").siblings().css({"color": "#40a944", "border": "2px solid #40a944"});
    });
  </script>
</head>
<body>
  <ul>Parent
    <li>sibling 1</li>
    <li>sibling 2</li>
    <li>sibling 3</li>
    <li>sibling 4</li>
    <li>sibling 5</li>
  </ul>
</body>
</html>

When we execute the above program, the siblings() method will return all sibling elements of div element (which are all the li elements).

Example 2

Here, we are returning the elements with class name "one", that are siblings of the li element with class name "start" −

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
        $("li.start").siblings(".one").css({"color": "#40a944", "border": "2px solid #40a944"});
    });
  </script>
</head>
<body>
  <ul>Parent
    <li class="one">sibling 1</li>
    <li>sibling 2</li>
    <li class="start">sibling 3</li>
    <li>sibling 4</li>
    <li class="one">sibling 5</li>
  </ul>
</body>
</html>

After executing the above program, it returns siblings of the li element with class name "start" with green colored border and green text color.

Example 3

In this example, we are selecting all sibling p elements of the div element −

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
        $("div").siblings("p").css({"color": "#40a944", "border": "2px solid #40a944"});
    });
  </script>
</head>
<body>
  <p>paragraph outside the div.</p>
  <div><b>This is a div element.</b>
    <p>paragraph inside the div.</p>
    <p>paragraph inside the div.</p>
  </div>
  <p>paragraph outside the div.</p>
</body>
</html>

When we execute the above program, the siblings() method will return all sibling elements of div element (which are all the p elements outside the div).

jquery_ref_traversing.htm
Advertisements