• jQuery Video Tutorials

jQuery element + next Selector



The element + next selector in jQuery is used to select the immediately following sibling of a specific element.

To understand this better, let us consider the following two example scenarios −

Scenario 1: There are two <p> elements immediately after a <div> element.

$("div + p"):  This will only select the first <p> element, because it only selects one element (the other <p> element will be ignored). 

Scenario 2: If you have a <div> element, right after that a <h2> element, and then a <p> element.

$("div + p"):  This will not select the <p> element, because the immediate element of <div> is <h2>, not <p>. 
This selector selects only the immediate next sibling element. If you need to select multiple siblings or elements that are not immediately next, consider using other traversal methods such as next(), nextAll(), or nextUntil().

Syntax

Following is the syntax of jQuery element + next Selector −

("element + next")

Parameters

Here is the description of the above syntax −

  • element: Any valid jQuery selector.
  • next: Specifies the element that should be the immediate element of the `element` parameter.

Example 1

In this example, we are using the jQuery element + next Selector to select the <p> element that is next to the <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.</p></div>
    <p>Paragraph element.</span>
    <p>This is another paragraph.</p>
</body>
</html>

After executing the above program, we can see that the immediate <p> element is selected and highlighted.

Example 2

In this example, we are selecting the <p> element that is next to the <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.</p></div>
    <h2>Heading element.</h2>
    <p>Paragraph element.</p>
</body>
</html>

The above program will not select the <p> element, because the next element of the <div> element is <h2>.

jquery_ref_selectors.htm
Advertisements