Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: check for blank textNode

Tags:

javascript

dom

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

like image 265
user984003 Avatar asked Nov 12 '22 06:11

user984003


2 Answers

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

like image 157
user984003 Avatar answered Nov 15 '22 06:11

user984003


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.

like image 41
Xotic750 Avatar answered Nov 15 '22 06:11

Xotic750