Should't JavaScript ignore whitespace? Node quirk in Firefox

非 Y 不嫁゛ 提交于 2019-12-01 20:42:42

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.

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.

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