jQuery nth-child nth-of-type Not Working

2019-07-07 21:24发布

问题:

I need to insert a clearfix div after x amount of elements so that I can get nicely formatted columns.

I've tried both :nth-child and :nth-of-type and I only get a single div added after the first x items.

$('#content .product-layout:nth-child(3)').after('<div class="clearfix visible-lg"></div>');

Creates a div after the third .product-layout div.

$('#product-row div:nth-child(3)').after('<div class="clearfix visible-lg"></div>');

Creates a div after the third .product-layout div.

I need to create the div after each 3rd existing product-layout div.

What the heck am I doing wrong?

回答1:

You're missing n to select every third child element with class product-layout of #content:

$('#content .product-layout:nth-child(3n)').after('<div class="clearfix visible-lg"></div>');
// ----------------------------------  ^ here


回答2:

You need to use 3n for a repeated element list, :nth-child(3) selects only 3rd child where as :nth-child(3n) will select 3, 6, 9... etc

$('#product-row div:nth-child(3n)').after('<div class="clearfix visible-lg"></div>');

Demo: Fiddle

  • :nth-child