使用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
和count个元素节点。
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屋!
查看全文