Keith Carter
Keith Carter

Reputation: 456

jQuery nth-child confusion

On this page: https://weargustin.com/store?filter=all

Why is the first element of this selector:

$('div.funded.product:nth-child(3n)')

The second element of

$('div.funded.product')

?!

Upvotes: 0

Views: 145

Answers (2)

PSL
PSL

Reputation: 123739

I think you want to select every 3rd of that type so you should try using nth-of-type instead of nth-child since there are many other siblings to start with other than div.funded.product. For instance you have the div .product.funding also coming in as the child of the same parent.

$('div.funded.product:nth-of-type(3n+1)')

See :nth-of-type

Upvotes: 2

Owen Allen
Owen Allen

Reputation: 11958

The problem is that nth-child loops over all children and tests them against the selector. It does not use the selector and then loop over those that match. So as PSL mentioned, the other items you have which are siblings are throwing the whole thing off.

Here's an example fiddle to break it down: http://jsfiddle.net/Ga5Jq/

<div>
        <p>test</p>
        <span>1</span>
        <span>2</span>
        <span>3</span>
</div>


$(function() {
    alert($("div span:nth-child(3n)").html());
});

The above code alerts 2 because the second span is really the third child of div matching the selector, span.

Upvotes: 3

Related Questions