[英]Get all childs od childs of (…) childs of parentNode
Good morning, or in other words: "Hello World". 早上好,换句话说:“ Hello World”。
This may sound like a stupid beginners question but am not sure if I just missed something: 这听起来像是一个愚蠢的初学者问题,但是不确定我是否错过了一些事情:
If in HTML you have a DIV with two children (say div as well) you can say .childElementCount will result in 2. To access them you can say .children[0] and children[1] 如果在HTML中有两个孩子的DIV(也称div),则可以说.childElementCount的结果为2。要访问它们,可以说.children [0]和children [1]。
But, if the children also have children and those also have children..... How can I determine the total amount of elements within a DOM Node? 但是,如果子代也有子代,而那些子代也有子.....如何确定DOM节点中元素的总数?
Do I really need to check for "hasChildren" or is there an easy way to get all sub and sub-sub-elements for a specific dom element which I missed? 我是否真的需要检查“ hasChildren”,还是有一种简单的方法来获取我错过的特定dom元素的所有子元素和子元素?
You can use querySelectorAll
with *
as it will select all the DOM elements inside it. 您可以将querySelectorAll
与*
一起使用,因为它将选择其中的所有DOM元素。 Then count the elements using .length
property. 然后使用.length
属性计数元素。
var x = document.querySelectorAll("#parent *").length; console.log(x);
<div id="parent"> <div> <div> </div> <div> </div> </div> <div> <div> <div> <span></span> </div> </div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.