For a shopfront I’m building a simple selector that allows showing and hiding elements based on their class.
I’m using the nth-child() selector to add a class to every 3rd element, but even though the selector does work in showing and hiding elements, my script doesn’t add the class to the third element after making a selection.
The code I’m using is quite big (and can definitely be optimized) so for an example of what I mean, please take a look at this jsFiddle.
What am I doing wrong?
You are misunderstanding what nth-child does.
You expect
.myclass:nth-child(3n)to select each 3rd occurrence of.myclass.What it really does is select each
nth-childelement of it’s parent node regardless of class. It basically acts as a combined selector. In your caseIn your case you should use: