简体   繁体   English

如何计算具有javascript类的父节点的所有子节点?

[英]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.

相关问题 如何在事件侦听器中将父节点与其所有子节点相关联? jQuery / JavaScript - How do I associate a parent node with all of its children in an event listener? jQuery / JavaScript jquery / javascript:如何从父元素的所有子元素中删除“活动”类? - jquery/javascript: How do I remove the 'active' class from all the children of a parent element? 如何使用Javascript从父级中的所有子级中删除活动类 - How to remove the active class from all children in a parent using Javascript 我如何选择某些类别的所有元素,但不包括属于此类的子元素? - How can I select all elements of certain class except those that are children of this? 如何删除父节点及其所有子节点 - How to remove a parent node with all its children 如果所有孩子都是“显示:无”,我该如何隐藏父 div - how can I hide parent div if all the children are "display:none" 如何使用 javascript 来计算屏幕上具有某个 class 的项目数? - How can I use javascript to count the number of items on screen with a certain class? jQuery如何计算一种类型的所有xml节点与某种类型的父节点 - jquery how to count all xml nodes of one type with a certain type of parent node 我有很多班级新闻的家长元素,我该如何从同一个父母的其他孩子中选择一个孩子 - I've many parent elements with class news how can i select children on one from other children in same parent 如何使用Javascript获取所有孩子(即孩子的孩子)? - How do i get all children (ie children of children) with Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM