Should't JavaScript ignore whitespace? Node quirk in Firefox

此生再无相见时 提交于 2020-01-21 12:42:14

问题


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?


回答1:


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.




回答2:


I thought that JavaScript was white space insensitive. So why does it change nodeLength from 1 to 3?

Firefox is behaving correctly.

This isn't a JavaScript issue. The DOM counts "whitespace only" areas as text nodes, and so the JavaScript is correctly returning all child nodes it finds.

It was older IE that behaved differently, where such whitespace only areas would be ignored. This has been corrected since IE9.

Basically, anything that appears in the page is represented as a DOM node.

I personally prefer to compress my HTML. It not only reduces the download time, but it also makes the DOM smaller with less to occupy memory, and fewer undesired nodes to work around.



来源:https://stackoverflow.com/questions/20553085/shouldt-javascript-ignore-whitespace-node-quirk-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!