jquery
  1. jquery-siblings

jQuery siblings() Method

The jQuery siblings() method is used to select all the sibling elements of a selected element. Siblings are the elements that share the same parent as the selected element.

Syntax

The basic syntax for using the siblings() method in jQuery is as follows:

$(selector).siblings(filter);

Here, selector is the element you want to select the siblings for and filter is an optional parameter to filter the siblings based on a specific criteria.

Use

The siblings() method is useful when you want to apply a certain style or behavior to all the sibling elements of a selected element. For example, you might want to highlight all the links in the sibling list items of a navigation menu when the user hovers over a particular list item.

Example

Here is an example of using the siblings() method to select all the sibling elements of a selected element and apply a class to them:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery Siblings Method Example</title>
  <style>
    /* Add some styling to visualize the effect */
    .highlight {
      color: red;
      font-weight: bold;
    }
  </style>
</head>
<body>

  <ul>
    <li class="selected">Home</li>
    <li>About</li>
    <li>Services</li>
    <li>Contact</li>
  </ul>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
      $("li.selected").siblings().addClass("highlight");
    });
  </script>

</body>
</html>
Try Playground

In this example, we have a navigation menu with a selected class applied to the Home list item. We use the siblings() method to select all the other list items and add a highlight class to them when the page loads.

Summary

The jQuery siblings() method is a useful tool for selecting all the sibling elements of a selected element and applying a style or behavior to them. With the optional filter parameter, you can narrow down the selection based on a specific criteria. Use this method to create dynamic and interactive webpages with ease.

Published on: