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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('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.
Now take for example the power of nth-child selectors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('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