I’m making a simple jquery counting function that adds the following classes:
- First & Last
- Even & Odd
- nth-item-# (counts in order)
- nth-item–# (counts backwards)
I have the first two done pretty easily, but the second two are giving me trouble since I’m new to jQuery/Javascript
You can see the jsfiddle here:
http://jsfiddle.net/JamesKyle/y7hBQ/
This is the code I’m currently using:
$(document).ready(function() {
$('.count, ul').each(function() {
var countChildren = $(this).children();
$(countChildren).filter(':even').addClass('even');
$(countChildren).filter(':odd').addClass('odd');
$(countChildren).first().addClass('first');
$(countChildren).last().addClass('last');
var numberOfChildren = $(countChildren).size();
// $(countChildren).addClass('nth-item-' + #);
// ⬆
// Fill with the elements number
// $(countChildren).addClass('nth-item--' + #);
// ⬆
// Fill with the elements number (negative count)
});
});
I’m only focusing on the commented out lines
Again here is the jsfiddle:
http://jsfiddle.net/JamesKyle/y7hBQ/
Thanks ahead of time!
UPDATE :
I have two solutions below, I plan to use this on a very large scale so if you could recommend what would be the most efficient way it would help me a lot! Thanks!!
If every effiency count then you should consider reduce iterations;
This way you iterate on children only one time. When you use filters, it iterates and filters items according to your filter. jsFiddle here.
A little benchmark is here.