The jQuery next() method can be used to return the next sibling element for the selected element. Siblings are the elements of the same matching parent element. The method access all the matching elements to find the next sibling element.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select and find its next sibling elements. You can use the element tag name, class name, or id to select. It is a required field. |
filterElement | It is the element to specify for the next sibling search. It is an optional field. |
jQuery next() Method to Get Next Sibling Element
If you want to get the next sibling element, you have to use the method as given below. The example contains the list elements and the method gets the middle item as the matching sibling element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("ul li.middle").next().css({"color":"orange","border":"1px solid red"}); }); }); </script> <ul> <li class="first">First li item</li> <li>Second li item.</li> <li class="middle">Middle li item.</li> <li>Forth li item</li> <li class="last">Last li item.</li> </ul> <button type="button" class="mybtn">Click to Get Next</button> |
Output
- First li item
- Second li item.
- Middle li item.
- Forth li item
- Last li item.
When you click the button given above, it selects the sibling element of the list item. The above example showing the element after you click the button.
Return Specified Matching Next Sibling Element
You can also return the next sibling by specifying the element as the parameter of the jQuery next() method. The class the last list item is the parameter of the method. It then selects the last element of the list item.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.mysfbtn').click(function(){ $("ul li").next(".last").css({"color":"red","border":"1px solid yellow"}); }); }); </script> <ul> <li>1st item</li> <li>2nd item</li> <li>3rd item</li> <li class="last">Last item</li> </ul> <button type="button" class="mysfbtn">Click to Get Next</button> |
Output
- 1st item
- 2nd item
- 3rd item
- Last item
Click the button given above to return the specified matching next sibling element. When you click the button given above, it highlights the last item of the list element.
You may also like to read
I hope you like this tutorial on jQuery next() method. If you have any queries regarding the tutorial, please comment below.
References