5

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!)

user984003
  • 28,050
  • 64
  • 189
  • 285

3 Answers3

3

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

Community
  • 1
  • 1
user984003
  • 28,050
  • 64
  • 189
  • 285
2

Something like this

HTML

<div id="test1">        
    </div>
<div id="test2">    &nbsp;      
    </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.

Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • You're testing an element. OP is testing a text node. –  Apr 30 '13 at 22:18
  • Yes, that'll work. I wonder if it works with all whitespace HTML entities. –  Apr 30 '13 at 22:40
  • I believe it should (not tested all), but it would be easy to test, just fork the jsfiddle and put them in there. – Xotic750 Apr 30 '13 at 22:42
-4
if ( element.textContent.trim() ) ...

EDIT, really meant to say:

if ( element.innerHTML.trim() ) ...
dandavis
  • 16,370
  • 5
  • 40
  • 36