What is the best way to check if a DOM text node is blank? By blank I mean only spaces, returns, tabs, etc. If it contains a nbsp; then it is NOT blank.
I was doing:
element.nodeValue.trim().length != 0
However, this also gets rid of nbsp;, which I do not want.
(It's for a Chrome extension so use of trim is OK - no IE!)
I ended up replacing nbsp; with a char and then trimming.
element.nodeValue.replace(/\u00a0/g, "x").trim().length != 0
Based on Replacing from javascript dom text node
Something like this
HTML
<div id="test1">
</div>
<div id="test2">
</div>
Javascript
var test1 = document.getElementById("test1");
var test2 = document.getElementById("test2");
function escapeHTML(str) {
var pre = document.createElement('pre');
pre.appendChild(document.createTextNode(str));
return pre.innerHTML;
}
console.log(escapeHTML(test1.textContent).trim().length === 0);
console.log(escapeHTML(test2.textContent).trim().length === 0);
On jsfiddle
output is
true
false
Or with nodeValue
Javascript
var test1 = document.getElementById("test1").firstChild;
var test2 = document.getElementById("test2").firstChild;
function escapeHTML(str) {
var pre = document.createElement('pre');
pre.appendChild(document.createTextNode(str));
return pre.innerHTML;
}
console.log(escapeHTML(test1.nodeValue).trim().length === 0);
console.log(escapeHTML(test2.nodeValue).trim().length === 0);
output
true
false
On jsfiddle
See Node.nodeValue and Node.textContent
Node.nodeValue
Returns or sets the value of the current node.
The following table shows the return values for different elements: ...
Text: content of the text node
Node.textContent
Gets or sets the text content of a node and its descendants.
In the first case I get the text content of the div element and it descendants.
In the second case I choose the first text node of the div, which happens to be the first child node, and get it's node value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With