JavaScript应该忽略空格吗? Firefox中的节点怪癖 [英] Should't JavaScript ignore whitespace? Node quirk in Firefox
问题描述
在Firefox的最新版本中遇到了这个bug,我不知道是什么原因导致了这种情况。 HTML
< div>< h1 id =heading>第一标题< / h1> ; / div>< div>< h1>第二标题< / h1>< / div>
JavaScript
var allDivNodes = document.getElementsByTagName(div);
console.log(allDivNodes [0] .childNodes);
console.log(allDivNodes [1] .childNodes);
console.log(allDivNodes [0] .childNodes.length);
console.log(allDivNodes [1] .childNodes.length);
我得到的结果如下:
$ b $这是怪癖。如果我在HTML代码中添加空格并运行相同的脚本,我得到这个结果:
新的HTML。 JavaScript保持不变
< div>
< h1 id =heading>第一个标题< / h1>
< / div>
< div>
< h1>第二标题< / h1>
< / div>
新结果
I认为JavaScript是空白不区分的。那么为什么将nodeLength从1更改为3?
您可以使用 children ,而不是 childNodes
,因为格式化你引入了一些文本节点(是的,它们是类型3的节点不仅仅是一些空格),而 childNodes
将返回所有这些节点。
的console.log(allDivNodes [0] .children.length);
或者使用childNodes,您可以循环使用 nodeType == = 3
。
同样你也有 childElementCount ,它将为您提供childElement计数,并忽略文本节点。
I encountered this "bug" in the latest verison of firefox and I don't know what causes this behavior and which is the correct result.
HTML
<div><h1 id="heading">First Title</h1></div><div><h1>Second Title</h1></div>
JavaScript
var allDivNodes = document.getElementsByTagName("div");
console.log(allDivNodes[0].childNodes);
console.log(allDivNodes[1].childNodes);
console.log(allDivNodes[0].childNodes.length);
console.log(allDivNodes[1].childNodes.length);
The result I get is the following:
And here is the quirk. If I add spaces in my HTML code and run the same script I get this result:
NEW HTML. JavaScript stays the same
<div>
<h1 id="heading">First Title</h1>
</div>
<div>
<h1>Second Title</h1>
</div>
New Result:
I thought that JavaScript was white space insensitive. So why does it change nodeLength from 1 to 3?
You could use children instead of childNodes
, because of formatting you introduced some text nodes (Yes they are nodes with type 3 not just some whitespace) and childNodes
will return all of them.
console.log(allDivNodes[0].children.length);
Or with childNodes you can loop though and ignore the ones with nodeType === 3
.
Also similarly you have childElementCount as well which will give you the childElement count and will ignore text nodes.
这篇关于JavaScript应该忽略空格吗? Firefox中的节点怪癖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!