Reputation: 2764
So let's say I have a very basic page with a body, a single div, and a paragraph element inside with some text.
<body>
<div>
<p>some text</p>
<div>
</body>
Depending on the browser, the body / div elements will have text nodes (nodeType === 3, nodeValue === "--blank--"). However the P element will have a legitimate text node with nodeValue === "some text".
What I am wondering is what is that "nodeValue" (--blank--) of a 'fake' text-node that represents whitespace equal to, as I want to write an if test that will let me filter out the fake text nodes.
Example:
var body = document.getElementsByTagName("body")[0]; // shortcut to body element.
console.log(body.childNodes[0].nodeValue) // maps to one of the fake text nodes that are blank.
// returns a blank line. What is that "blank" equal to? It's not 'null' or "" or undefined...
Cheers, Alex
Upvotes: 0
Views: 4174
Reputation: 147363
You could use a regular expression such as:
var re = /\S/; // Match non-whitespace
if (node.nodeType == 3 && re.test(node.nodeValue)) {
// text node has something other than whitespace
}
noting that there are slight variations in what browsers consider whitespace and what is matched by \s
, but that may not be important here.
Upvotes: 2
Reputation: 322452
Just trim()
[docs] the whitespace, and see if there's anything left:
if( body.childNodes[0].nodeValue.trim() ) {
// more than white space
} else {
// just white space
}
If there was only white space, you'll end up with a falsey value. Otherwise it will be truthy.
The docs link provides the following compatibility shim:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
Upvotes: 2