Friday, January 25, 2013

jQuery - iterating on every nth object in a collection

In jQuery it is often necessary to iterate over a collection to manipulate multiple objects. A common mistake when doing so is to iterate over every object when it is not needed.

For example, let's say I have an unordered list where the 5th item in each list needs a CSS class added to it. A common way to do this would be like so:
$('ul li').each(function(i){
if((i+1) % 5 == 0){
$(this).addClass('bold');
}
});

This will iterate over the entire collection of list-items and track the iterations in i. It will compare each iteration of i to modulus 5, and if this is a iteration that has a modulus 5 of 0, then add the CSS class.

Now take for example the power of nth-child selectors.
$('ul li:nth-child(5n)').addClass('bold');

With one line we accomplish exactly the same result, but with very few operations. It is important here to note that I used "5n" and not "5". Simply using "5" would only bold the 5th li in every ul affected, while "5n" will add the class to each multiple of 5 in all ul's affected.

No comments:

Post a Comment