ClosDesign ClosDesign - 10 months ago 57
jQuery Question

jquery eq() and looping

I have a few questions about the eq() property of jQuery and how to multiple selecting.

I have a list with 15 items in it. I want every 1st, 6th, and 11th item to have a background color. 2nd, 7th, and 12th have another background color, 3rd, 8th, and 13th have a background color, etc, etc, etc.

I though about using the eq() property but if my list needs to grow, I don't want to manually add the background color in the jQuery for every time someone adds a new list item.

If my list needs to grow then the next color will coincide with the one that is 5 behind it.
So the 16th list item will need the same background as the 1st.

Does that make sense?

How would I accomplish this in jQuery. A loop? how would I do this.

Thanks in advance.

Answer Source

Try using :nth-child instead of eq(). See below,


$(document).ready(function () {
  $('#myList li:nth-child(5n+1)').addClass('pink');
  $('#myList li:nth-child(5n+2)').addClass('blue');
  $('#myList li:nth-child(5n+3)').addClass('yellow');