What is the next() method in jQuery?

Overview

The next() method in jQuery locates the next element of the selected group. For example, if we have <div> before an <ul> element, using the next() will help us locate <ul>. Moreover, we don't need to know the next element for this.

Syntax

$(selector).next(filter)

Traversing in jQuery

jQuery traversing helps us drill down or locate HTML elements relative to other elements. It selects an element first, and goes through the selection until the desired element is reached. Let's see an example.

Example

Using the jQuery next() method

Code explanation

Line 10: We first select the <div> element with the start class. We then use jQuery to add some styling to the next element.

To better understand how this works, we can play with the sample code above. We can add an element below the <p> element and use jQuery to get the next element.

The children elements are enclosed within an element. In the example below, the <div> element has two children <p>.

<div>
<p>
Hi
</p>
<p>
Bye
</p>
</div>
<h1>
</h1>

Meanwhile, the next element is the one that comes after the element that we are pointing to. In the example below, the next element of the <div> is <h1>.

<div>
<p>
Hi
</p>
<p>
Bye
</p>
</div>
<h1>
</h1>

Free Resources