Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove class from element and add to next element

I have a list of links, one has the class active.

On my next button click id like to remove the class from the current element and add it to the next only I cant seem to get it to add?

Ive made a fiddle to hopefully explain my problem, any help would be great, thanks

http://jsfiddle.net/h6D4k/

$('.next').click(function(){
    $('ul.pagination').find('a.active').removeClass('active');
    $('ul.pagination').find('a.active').next('a').addClass('active');
    return false;
});
like image 477
Liam Avatar asked Dec 19 '12 16:12

Liam


2 Answers

One of the jQuery most usable conveniencies is that its methods are (usually) chainable - in other words, they return the very object they are called from. So you can simply write this:

$('ul.pagination').find('a.active').removeClass('active').closest('li')
                  .next('li').find('a').addClass('active');

... as it's <li> elements that should be 'nexted', not <a> ones. But in fact, you shouldn't probably discard 'active' altogether if it's the last element in question:

var $a      = $('ul.pagination').find('a.active'),
    $li     = $a.closest('li'),
    $nextLi = $li.next('li');

if ($nextLi.length) {
   $a.removeClass('active');
   $nextLi.find('a').addClass('active');
}
like image 187
raina77ow Avatar answered Oct 03 '22 04:10

raina77ow


This is actually what you want based on your html structure in you fiddle. http://jsfiddle.net/h6D4k/1/

$('ul.pagination').find('a.active').removeClass('active').parent()
                  .next().find('a').addClass('active');
like image 29
Jack Avatar answered Oct 03 '22 05:10

Jack