Javatpoint Logo
Javatpoint Logo

jQuery next() method

The next() method is an inbuilt method in jQuery, which returns the next sibling of the selected element. This method traverses forwards along with the next sibling of DOM elements.

Syntax

This method accepts an optional parameter that is used to specify a selector expression that narrows down the searching of the next sibling.

Let's see some of the illustrations to understand the working of the next() method.

Example1

In this example, there is a div element, including three child elements that are an ul element, a heading h2, and a paragraph element. Here, we are using the next() method to get the next sibling of the h2 element. We are not using the optional parameter of the next() method.

On clicking the given button, the next() method will return the p element, as it is the immediate next sibling of the heading h2.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery next() method

After clicking the given button, the output will be -

jQuery next() method

Example2

In this example, we are using the optional parameter of the next() method to narrow down the search. Here, there is a div element including multiple children. We are finding the next sibling of the h2 element. There are many h2 heading elements with different siblings. But we are passing the p element as the optional parameter of the next() method. So, the method will only return the p elements that are the immediate next sibling of the h2 element.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery next() method

In the above screenshot, we can notice the siblings of the h2 element. But the method will return only the p element, as we have passed the p element as the optional parameter of the next() method. After clicking the given button, the output will be -

jQuery next() method

Example3

It is another example of using the next() method. On clicking the given button, the next() method will trigger and start traversing through the DOM elements. The method will return the immediate next sibling of each div element and changes the background-color of corresponding div to red.






Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA