March 17, 2012
Jquery last selector solution
Question by Dejo Dekic
I have created this Fiddle with this code:
This is my problem I want to make same behavior by selecting last li (fifth) tag but not the fourth like in this example ,but I don’t know how to accomplish that:(
I hope that someone can help me with this…THX!!
$(document).ready(function() {
$("button").click(function() {
$('.active').removeClass('active').next('li').addClass('active')
if ($('ul li:last').hasClass('active')) {
$('ul li:last').removeClass('active')
$('ul li:first').addClass('active')
}
});
});
Answer by Rob W
You should put part in an else
block. Otherwise, both methods will run twice for the last list item, causing the last element to be “skipped”.
A better solution (demo: http://jsfiddle.net/9dF22/5/ ):
$(document).ready(function() {
$("button").click(function() {
var $li = $('ul li'),
$active = $li.filter('.active:first'),
$next = $active.next();
$active.removeClass('active');
if ($next.length) { // length === 0 if there is no next one
$next.addClass('active');
} else {
$li.first().addClass('active');
}
});
});
Demo: http://jsfiddle.net/9dF22/3/
$(document).ready(function() {
$("button").click(function() {
if ($('ul li:last').hasClass('active')) {
$('ul li:last').removeClass('active')
$('ul li:first').addClass('active')
} else {
$('.active').removeClass('active').next('li').addClass('active')
}
});
});