tags:

views:

4628

answers:

3

I have a list in a ul that is in an ASP repeater. The list is set to overflow with a scrollbar and to only show 16 lis at a time. Is there a jQuery count function that I can use that would allow me to select every "16th" li and add a specific class to it?

Selecting the last one won't work because the 16th div is not the last div since it is in a repeater.

+9  A: 

Yes there is, it's called :nth-child.

Sample:

$("ul li:nth-child(16n)").addClass("sixteenth");
Jason Berry
Right, I understand that. But I want to get the "16th","32", etc...Would this function do that?
I've modified it, yes it will. Just change (16) to (16n).
Jason Berry
Perfect, that's exactly what I was looking for. Thanks!
Does this apply the selection rules with jQ or with the browser? I've noticed nth-child is not supported by FF3. If jQ is doing it by itself then there's no problem.
Karl
jQuery does it by itself.
Jason Berry
@Json fantastic trick! should go into jQuery Cheat-sheet
TheVillageIdiot
If this is the correct answer please mark it as correct! :)
Jason Berry
A: 

If you want to apply class to every element after 16th then you can use :gt(index) selector.

$("ul li:gt(16)").addClass("CLASS_NAME");

remember :gt, :lt etc selectors use zero based index.

for every 16th ofcouse you can use :nth-child(index)

$("ul li:nth-child(16)").addClass("CLASS_NAME");

remember :nth-child based selectors use 1 for first element.

TheVillageIdiot
well this method ":nth-child(index)" will only select the 16th li. I need it to then grab the 32nd, 48th,.....
Yes and for that http://stackoverflow.com/questions/1181113/can-i-count-elements-using-jquery/1181187#1181187 will work!!
TheVillageIdiot
So will http://stackoverflow.com/questions/1181113/can-i-count-elements-using-jquery/1181114#1181114 - but with far less code :)
Jason Berry
sure @Jason only you edited it after I've posted the comment!
TheVillageIdiot
+1  A: 

You could try an .each function:

$("ul li").each(function(index, domEle) {
    if (index%16==0) {
          $(domEle).addClass("CLASS_NAME");
    }
});
Jason
what does domEle represent?
Isn't this option a bit heavy-handed? jQuery already supplies the ability to do what he wants *without* iterating over the entire list! See my answer for an example of the nth-child selector.
Jason Berry
it works, though. your solution is, how you say, eleganter, tho :)
Jason