使用javascript计算元素的直接子元素 [英] Use javascript to count immediate child elements of an element
本文介绍了使用javascript计算元素的直接子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以获得一个元素的所有后代的数量,但我似乎不能只针对直接子元素.这是我目前所拥有的.
I can get the count of all descendants of an element, but I can't seem to target just the immediate children. Here's what I have at the moment.
var sectionCount = document.getElementById("window").getElementsByTagName("section").length;
我玩过其他东西和不同的语法,但我似乎无法理解.
I've played with other stuff and different syntax, but I can't seem to get it.
jQuery 等效项是:
The jQuery equivalent would be:
var sectionCount = $("#window > section").length;
但我只需要执行这个 javascript.
But I need to do this javascript only.
推荐答案
使用 DOM 选择器接口 (querySelectorAll).
Use the DOM selector interface (querySelectorAll).
var selectionCount = document.querySelectorAll("#window > section").length;
如果你想要一个向后兼容的解决方案,循环遍历 childNodes
并计算元素节点.
If you want a backwards compatible solution, loop through childNodes
and count element nodes.
var w = document.getElementById('window');
var count = 0; // this will contain the total elements.
for (var i = 0; i < w.childNodes.length; i++) {
var node = w.childNodes[i];
if (node.nodeType == Node.ELEMENT_NODE && node.nodeName == "SECTION") {
count++;
}
}
这篇关于使用javascript计算元素的直接子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文