为什么`childNodes`返回的数字比我预期的要大? [英] Why does `childNodes` return a number larger than I expect?
问题描述
您能否看看这个jsFiddle示例,并告诉我为什么数字11会被提醒比'5'(数量< li>
元素)?
来自jsFiddle:
HTML
< ul id =list>
< li>牛奶< / li>
< li>黄油< / li>
< li>鸡蛋< / li>
< li>橙汁< / li>
< li>香蕉< / li>
< / ul>
JavaScript
var list = document.getElementById('list');
var list_items = list.childNodes;
alert(list_items.length);
childNodes
取决于使用的浏览器,将返回文本节点以及作为父节点的子节点的标记。因此从技术上讲,< li>
标签之间的空白也将被计入 childNodes
中。
为避免处理它们,您可以检查 nodeType!= 3
。 下面是节点类型列表。
var list = document.getElementById('list');
var list_items = list.childNodes;
var li_items = [];
for(var i = 0; i< list_items.length; i ++){
console.log(list_items [i] .nodeType);
//添加所有< li>如果(list_items [i] .nodeType!= 3){
li_items.push(list_items [i]);则跳过文本节点
。
}
}
Could you please look at this jsFiddle example, and tell me why the number '11' is alerted rather than '5' (the number of <li>
elements)?
From jsFiddle:
HTML
<ul id="list">
<li>milk</li>
<li>butter</li>
<li>eggs</li>
<li>orange juice</li>
<li>bananas</li>
</ul>
JavaScript
var list = document.getElementById('list');
var list_items = list.childNodes;
alert(list_items.length);
The childNodes
, depending on the browser used, will return the text nodes, as well as the tags that are children of the parent node. So technically, the whitespace in between the <li>
tags will also be counted among the childNodes
.
To avoid processing them, you may check that nodeType != 3
. Here is a list of node types.
var list = document.getElementById('list');
var list_items = list.childNodes;
var li_items = [];
for (var i=0; i<list_items.length; i++) {
console.log(list_items[i].nodeType);
// Add all the <li> nodes to an array, skip the text nodes
if (list_items[i].nodeType != 3) {
li_items.push(list_items[i]);
}
}
这篇关于为什么`childNodes`返回的数字比我预期的要大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!