<div class="parent">
<div class="child-class">
<div>
<div class="child-class">
<div>
<div class="child-class">
<div>
</div>
我需要使用 jQuery
添加一个类到第二个 child-class
最佳答案
通过 CSS 选择器寻址父级的第二个子级:
$('.parent > .child-class:nth-of-type(2)').addClass('your-class');
使用 nth-of-type
而不是 nth-child
的优势在于可以更精确地选择您想要的内容。 nth-child
将选择您 parent 的任何 child 。 nth-of-type
只会选择特定类型的 child (在本例中为 class child-class
)。
关于javascript - 如何将类添加到div的父子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47754681/