[英]How can I count all the children of a parent node that have a certain class with javascript?
In javascript preferably. 最好在javascript中。 For example:
例如:
<div id="parent">
<div class="one"></div>
<div class="one"></div>
<div class="one"></div>
<div class="two"></div>
<div class="two"></div>
</div>
how would I count the number of child elements with class "one" (3)? 我如何计算“一”类(3)的子元素数量? Thank you.
谢谢。
You can use querySelectorAll . 您可以使用querySelectorAll 。
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors.
返回与指定选择器组匹配的文档中的元素列表(使用文档节点的深度优先顺序遍历)。
selectors is a string containing one or more CSS selectors separated by commas.选择器是一个字符串,包含一个或多个用逗号分隔的CSS选择器。
You can refer all CSS selectors here . 您可以在此处引用所有CSS选择器。
In this case #parent > .one
will search for elements with class one
which are immediate children of element with id parent
. 在这种情况下
#parent > .one
将搜索类元素one
这与id元素的直接子parent
。
var count = document.querySelectorAll("#parent > .one").length; console.log(count);
<div id="parent"> <div class="one"></div> <div class="one"></div> <div class="one"></div> <div class="two"></div> <div class="two"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.