• jQuery Video Tutorials

jQuery element ~ siblings Selector



The element ~ siblings Selector in jQuery is used to select all sibling elements that come after the specified element. The "~" selector is used in conjunction with a specific element selector to specify the siblings that come after it.

Syntax

Following is the syntax of jQuery element ~ siblings Selector −

("element ~ siblings")

Parameters

Here is the description of the above syntax −

  • element: Specifies the element after which sibling elements are selected.
  • siblings: Elements that are siblings of the `element`.

Example 1

In the following example, we are using the jQuery "element ~ siblings" Selector to select all siblings of <p> elements that comes after the <h2> element −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Select all siblings of 'p' elements that come after the first 'p'
            $("h2 ~ p").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <h2>Heading element.</h2>
    <p>This is the second paragraph.</p>
    <p>This is the third paragraph.</p>
    <p>This is the fourth paragraph.</p>
</body>
</html>

After executing the above program, the <p> sibling elements of <h2> will be selected and highlighted with yellow background color.

Example 2

Here, we are selecting all the <p> elements that are siblings of <div> element −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("div ~ p").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div style="border: 2px solid black;">Div element.</div>
    <h3>Heading element.</h3>
    <p>This is the third paragraph.</p>
    <p>This is the fourth paragraph.</p>
    <h3>Heading element.</h3>
</body>
</html>

Even though there are heading elements after the parent element <div>, only the <p> elements will be selected.

jquery_ref_selectors.htm
Advertisements