jQuery next() sibling, jQuery prev() With Example

Today we will look into jQuery next() and jQuery prev() functions. These are jQuery traversing functions that returns the next and previous sibling element of the selected HTML element. Here we are going to look more about these methods.

jQuery next() sibling

jQuery next() function returns the next sibling element of the selected element. We can provide an optional selector parameter to this method and the next() method will return the sibling element only if there is a matching selector.

Here is the general syntax for using jQuery next() method:

  • selector.next( [selectorExpression] )

selectorExpression is an optional string parameter passed to the method.

jQuery next() example

The following example demonstrates the jQuery next() usage.

In this example, We set the background color of the first div element with id="start" to red color. jQuery next() method triggers when the button is clicked and it starts traversing through the DOM elements.

jQuery next() method will return the div2 on the first click and changes the background color to red. Now div2 is the current element and clicking the next button will return the div3 and so on. This is how jQuery next method works.

Below is the output of jQuery next example.

jQuery next sibling, jQuery next element

You can try it yourself by clicking on the below button.

jQuery prev()

jQuery prev() method returns the previous sibling element of the selected element. We can provide an optional selector parameter to this method and the prev() method will return the sibling element only if there is a matching selector.

Here is the general syntax for using jQuery prev() method:

  • selector.prev( [selectorExpression] )

selectorExpression is an optional string parameter passed to the method.

jQuery prev() example

The following example demonstrates the jQuery prev() usage.

In this example, We set the background color of the last div element with id="startPrev" to red color. jQuery prev() method triggers when the button is clicked and it starts traversing through the DOM elements.

The prev() method will return the div5 on the first click and changes the background color to red. Now div5 is the current element and clicking the prev button will return the div4 and so on. This is how jQuery prev() method works.

Below is the output of jQuery previous sibling example.

jQuery prev(), jQuery previous sibling element

You can try it yourself by clicking on the below button.

That’s all for jQuery next() and prev() functions to get the next sibling and previous sibling of HTML elements. We will look into more jQuery traversing methods in coming posts.

By admin

Leave a Reply

%d bloggers like this: