jQuery Next Function Example

Let's have a closer look at the jQuery .next() function.

Demo Code Download


The .prev() and .next() functions can be used to reference the immediate preceeding element or next element in the set of matched elements (DOM hierarchy). You can also add a selector to the functions which acts as a filter on the elements, this is shown in the example. Lets have a look at an example of the next jQuery function in action. Further Reading »


jQuery Function Demo - jQuery4u.com

Demo: Referencing the previous/next elements in a list.

Run Demo View Code


The download package includes all the inline HTML, CSS, JavaScript, jQuery and images required for the .next() function demo so you can try it yourself and change as you please.

The full code listing for all jQuery functions have been now added to GitHub, you can get them there, we are making them work with the latest versions of jQuery!


<!-- Copyright 2011 jQuery4u.com -->
<!DOCTYPE html>
<title>jQuery Function Demo - jQuery4u.com</title>
    <script src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
    <script src="http://www.jquery4u.com/scripts/function-demos-script.js"></script>

    <script type="text/javascript">

    var JQFUNCS =
            /* ------------------------------ next() Demo ------------------------------ */
                run: function(id)
                    var $curr = $('#'+id+' li:first');
                    $('#'+id+' a').live('click', function(e)
                        if ($(this).hasClass("next"))
                            if ($curr.next().html()) {
                                $curr = $curr.next();
                            if ($curr.prev().html()) {
                                $curr = $curr.prev();

                reset: function(id)


    <style type="text/css" media="screen">
        .orangebg {background-color: #B1EFE9 !important; font-size:120%; }
        .demoarea ul {
            margin-top: 10px;
            font-size: 24px;
        .demoarea li {
            padding: 5px;


<p class="example">Demo: Referencing the previous/next elements in a list.</p>
<p><a href="#" id="next-demobtn" class="demobtn btn actionr">Run Demo</a> <a href="#" id="next-codebtn" class="codebtn btn actionr">View Code</a> <a href="#" id="next-resetbtn" class="resetbtn btn actionr" style="display: none;">Reset</a></p>
<div class="demoarea" id="next" style="border:1px solid orange; padding:20px;">
<a class="prev btn" href="#" style="text-decoration:none;">< Prev</a>  <a class="next btn" href="#" style="text-decoration:none;">Next ></a>

   <li>list item 1</li>
   <li>list item 2</li>
   <li>list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>

<!-- Copyright 2011 jQuery4u.com -->