jQuery Next Example
The aim of this example is to show you how to use the jQuery next()
method.
The jQuery next()
method is used for getting the next element of any HTML element.
This method takes the wanted elements type as an optional argument. For example, next('span')
is used to get the immediate following ‘span’ element.
By using this method, only the following sibling’s element is select, it’s child element will be ignore.
1. HTML
First of all you need to create a simple html document.
jQueryNextExample.html
<!DOCTYPE html> <html> <head> <title>jQuery Next Example</title> <script src="jquery-2.1.4.min.js"></script> </head> <body> </body> </html>
2. jQuery Next examples
2.1 Get Next Element Example
Let’s add the following simple html code.
<div id="div1">This is div1</div> <p>This is paragrah</p> <div>Others3</div> <button id="nextButton">next('div')</button>
In the following example, we need to get the next element regardless to its type. For that we don’t pass any parameter to the next()
method.
<script type="text/javascript"> $("#nextButton").click(function () { var nextElement = $("#div1").next(); alert(nextElement.text()); }); </script>
The result in the browser would be:
2.2 Get Next DIV Example
Let’s add the following simple html code.
<div id="div1" style="background:#f00">This is div1</div> <div>This is div2</div> <p>This is paragrah</p> <div>This is div3</div> <button id="nextButton">next('div')</button>
To get an element with a specific type, we need to pass the element type. As you can notice in the following example .
<script type="text/javascript"> $("#nextButton").click(function () { var nextElement = $("#div1").next("div"); $("div,p").css("background", ""); nextElement.css("background", "#f00"); }); </script>
The result in the browser would be:
3. Conclusion
jQuery provides a good and simple method to get the next element. This method helps us to navigate in the html document.This method takes the wanted elements type as an optional argument. For example, next('span')
is used to get the immediate following ‘span’ element. Calling this method without a parameter means getting the next element regardless its type.