5

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.

3 Answers 3

11

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

Sample:

$("ul li:nth-child(16n)").addClass("sixteenth");
Sign up to request clarification or add additional context in comments.

3 Comments

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).
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.
1

You could try an .each function:

$("ul li").each(function(index, domEle) {
    if (index%16==0) {
          $(domEle).addClass("CLASS_NAME");
    }
});

2 Comments

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.
it works, though. your solution is, how you say, eleganter, tho :)
0

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.

4 Comments

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 stackoverflow.com/questions/1181113/… will work!!
So will stackoverflow.com/questions/1181113/… - but with far less code :)
sure @Jason only you edited it after I've posted the comment!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.