jQuery .next() method get immediately following sibling of each element

Syntax and Description

.next([selector])

gets the immediately following sibling of each element in the set of matched elements, optionally filtered by a selector. selector (optional) is a string containing a selector expression to match elements against.

The return value is the new jQuery object.

Next class

The following code selects the next elements who has certain class.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!-- w  ww  . j a  va 2 s.  c  o  m-->
             $("button[disabled]").next(".selected").text("data");
        });
    </script>
    <style>
      .y { background:yellow; }
  </style>
  </head>
  <body>
    <body>
       <div><button disabled="disabled">First</button> - 
       <span class="selected"></span></div>
  </body>
</html>

Click to view the demo

Next tags

The following code selects the input element by name and then select tags next to it.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){<!--   ww w . j  av  a 2 s  . c om-->
          $("input[name='me']").next().text(" changed");
    });
    </script>
  </head>
  <body>
      <div>
        <input type="radio" name="me" value="A" />
        <span>data</span>
      </div>
      <div>
        <input type="radio" name="me" value="B" />
          <span>data</span>
      </div>
      <div>
        <input type="radio" name="me" value="C" />
        <span>data</span>
      </div>
  </body>
</html>

Click to view the demo

Find the next sibling and apply style

Find the very next sibling of each paragraph that has a class "selected".


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--  w  w w  . j a  v  a2  s.c o m-->

              $("p").next(".selected").css("background", "yellow");

        });
    </script>
  </head>
  <body>
    <body>
        <p>Hello</p>
        <p class="selected">Hello Again</p>
    </body>
</html>

Click to view the demo

Find the next and change text

The following code finds the next element after <p> and sets text.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  ww w . j a  va  2s  . c o m-->
            $("p").next().text("java2s.com");
        });
    </script>
  </head>
  <body>
    <body>
        <p>bad or .</p><span>good</span>
    </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities