[英]Selecting top level child
How do I add a class to the first level sections with jQuery and not other nested sections? 如何使用jQuery将类添加到第一级部分,而不是其他嵌套部分?
<div id="container">
<section>
<p>...</p>
</section>
<p>
<section>
<p>...</p>
</section>
</p>
<section>
<p>...</p>
</section>
<p>
<section>
<p>...</p>
</section>
</p>
</div>
$('#container section:first-child').addClass('section');
It seems to be adding to the very first section only 它似乎仅添加到第一部分
Use the child selector : 使用子选择器 :
$('#container > section').addClass('section');
And on a side note, you can't nest <p>
elements as it's invalid HTML. 另外,您不能嵌套
<p>
元素,因为它是无效的HTML。
您可以这样做:
$('#container > section').addClass('section');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.