There’s this simple thing i want to do.
I have to add a current class to the first <li> element and disabled class to others.
Currently i’m doing it this way:
$('#slideshow li:first').addClass('current');
$('#slideshow li').not(':first').addClass('disabled');
but i was wondering if we could di it in one line doing something like this:
$('#slideshow li').not(':first', function(){ $(this).addClass('current'); }).addClass('disabled');
Any enlightenment would be much appreciated. 🙂
jQuery chaining works because the method called is returning the same, or modified, result set that you’re running it on. So by filtering with
not()you’re returning the modified result set and won’t have access the original one again.You work around this by using
.end(), which does the following:End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.So either you do something like you’re doing (but with caching the result set), which I find a tad less confusing, and more readable:
Or you do it in one line, using
end(), which can potentially turn into a really long line of code: