jQuery nth-child nth-of-type Not Working

懵懂的女人 提交于 2019-12-24 01:43:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!