Johnny Derp Johnny Derp - 2 months ago 39
jQuery Question

jQuery select ul li items with next prev buttons

I'm trying to select li element with prev next buttons, currently using this code: but if you keep clicking next/prev it keeps going out of the ul element. any idea how i select inside ul ? Thanks!

here fiddle:

<ul class='selected' id="">
<li id="">1</li>
<li id="">2</li>
<li id="">3</li>
<div>Current tag:<span id="current-tag"></span></div>
<button id="prev">Previous</button>
<button id="next">Next</button>


(function($) {
$.fn.domNext = function() {
return this
.add(this.parents().filter(function() {
return $(this).next().length > 0;

$.fn.domPrevious = function() {
return this

$("#next").click(function() {
var $next, $selected = $(".selected");

$next = $selected.domNext().addClass("selected");
if ($next.length) {

$("#prev").click(function() {
var $prev, $selected = $(".selected");
$prev = $selected.domPrevious().addClass("selected");
if ($prev.length) {



Not sure about the plugin.. As that is surely an overkill for something simple.

But I would just write this up

var $first = $('li:first', 'ul');
var $last = $('li:last', 'ul');

// Have the first and last li's set to a variable
$("#next").click(function () {

    var $next;
    var $selected = $(".selected");
    // get the selected item
    // If next li is empty , get the first
    $next = $'li').length ? $'li') : $first;

$("#prev").click(function () {
    var $prev,
        $selected = $(".selected");
    // get the selected item
    // If prev li is empty , get the last
    $prev = $selected.prev('li').length ? $selected.prev('li') : $last;

Check Fiddle