Skip to content Skip to sidebar Skip to footer

Should't Javascript Ignore Whitespace? Node Quirk In Firefox

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

First T

Solution 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.

Solution 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.

Post a Comment for "Should't Javascript Ignore Whitespace? Node Quirk In Firefox"