Squrler
Squrler

Reputation: 3514

Having trouble with nth-child() selector

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?

Upvotes: 0

Views: 87

Answers (2)

Ashirvad
Ashirvad

Reputation: 2377

WORKING DEMO

Your code modified.. Replaced Line

 jQuery('.' + className).parent().children('.' + className + ':nth-child(3n) a').addClass('product_item_last');

Upvotes: 0

Torsten Walter
Torsten Walter

Reputation: 5802

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-child element of it's parent node regardless of class. It basically acts as a combined selector. In your case

select each third element that also has the class .myclass

In your case you should use:

$(".myclass").each(function(index, item){
    if (index % 3 == 0) {
        // do something
    }
})

Upvotes: 2

Related Questions