# March 16, 2013 at 4:05 pm
My goal is to only select every other element in a list that has a specific class. However, I’m finding that if there are elements in the list which do not contain the class, it seems to throw the selection off. This happens regardless of whether I use :nth-child of :nth-of-type.
Here is a code example of what I’m experiencing:
[http://codepen.io/micjamking/pen/mpvis](http://codepen.io/micjamking/pen/mpvis “CodePen: :nth-child/:nth-of-type bug”)
Ideally, the 2nd, 4th, … list item with a class of .diff should be selected, but it seems to be looking at the element instead of the class to determine the selection.
Appreciate any advice/help with this.# March 16, 2013 at 4:23 pm
I’m pretty sure :nth-child & :nth-of-type will work on any valid selector, ie. elements or classes.
[http://www.w3.org/wiki/CSS3/Selectors/pseudo-classes/:nth-child](http://www.w3.org/wiki/CSS3/Selectors/pseudo-classes/:nth-child “W3C: :nth-child”)
[http://www.w3.org/wiki/CSS3/Selectors/pseudo-classes/:nth-of-type](http://www.w3.org/wiki/CSS3/Selectors/pseudo-classes/:nth-of-type “W3C: :nth-of-type”)
It seems to be working in the code example, albeit incorrectly.# March 16, 2013 at 5:12 pm
This works fine for me: http://codepen.io/anon/pen/jdtuy
nth-child won’t work in your first example because there was a list item without a class that comes first. I’m pretty sure that’s what will cause it to be thrown off.
nth-of-type will work better in your example, but has smaller browser support (IE).# March 16, 2013 at 5:21 pm
I think Paulie D is correct now, :nth-child/:nth-of-type is only applied to elements, not classes.# March 16, 2013 at 5:56 pm
I think you probably need some JS/jQuery that goes through all elements with the class “diff”, and assigns a new class for every other one. I can’t think of any simpler way really:
If I understand correctly, you want every other item with that has class “div” to be styled. in this case, that would be 0-2-6-9.# March 16, 2013 at 6:12 pm
So it seems that :nth-of-type can apply to classes, but exhibits inconsistent behavior when doing so…# March 16, 2013 at 6:29 pm
@senff, since you have the index of the element in the set, you don’t need the `oddeven` variable :)
@micjamking, not a bug, the spec is talking about:
> an element that has an+b siblings before it in the document tree
> an element that has an+b siblings with the same expanded element name before it in the document tree
It doesn’t say anything about the classes on those siblings. `.diff:nth-child(even)`, you can read that as ‘every even child, that also has class diff’.# March 16, 2013 at 7:29 pm
@CrocoDillion: Ahhh, you are correct! That hurt my brain a bit trying to get my head wrapped around the definition, but your explanation cleared it up for me.
You must be logged in to reply to this topic.