问题
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
来源:https://stackoverflow.com/questions/22553536/jquery-nth-child-nth-of-type-not-working