Reputation: 9
Using Ajax to fetch XML data. question about blank text nodes
I read this question/ answer here Javascript/XML - Getting the node name
and this helped my understanding a ton about how the structure is set up however I still have a question or two.. when he mentions this part:
"Text node with a carriage return and some spaces or tab"
How would you test to see f you have gotten an empty text node like this? I've tried testing to see:
if nodeValue == null
nodeValue == "null"
nodeValue == ""
nodeValue == " "
none of these appear to be working
I figured maybe the length would be 0 so I tested for .length and it returned 5 (1 return key and 4 tabs.. added an extra tab in there and tested again it returned 6)
I then googled how to remove whitespace and used these:
.replace(/\s+/g, ' ');
.replace(/^\s+|\s+$/g, '');
Neither worked and still said the .length was still 5
Reason I want to test for this is because what if I don't know each of the element node names before hand or exactly how the DOM is set up.
Or is there a better way to navigate without bothering to check if a text node is just the tabs/spaces/return key?
Upvotes: 0
Views: 3927
Reputation: 1074989
.replace(/^\s+|\s+$/g, '');
works unless the spaces/tabs aren't really spaces and tabs, but one of the various other Unicode space-like characters. So I'm guessing you weren't quite using it correctly.
This would be how to use it:
if (!textNode.nodeValue.replace(/^\s+|\s+$/g, '')) {
// Node is empty
}
Example: Live Copy | Live Source
var xml = parseXml("<test>\n\t\t\t</test>");
var textNode = xml.documentElement.firstChild;
display("textNode.nodeValue.length = " +
textNode.nodeValue.length);
display('Is "empty"? ' +
(!textNode.nodeValue.replace(/^\s+|\s+$/g, '')));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Output:
textNode.nodeValue.length = 4 Is "empty"? true
(Where parseXML
is from this answer.)
But we really don't need to do a replace
(although the overhead of doing it is trivial). A test like this would do it:
if (/^\s*$/.test(textNode.nodeValue)) {
// The node is "empty"
}
That regular expression (zero or more whitespace characters with anchors at both ends) will only match a string that's already empty or consists only of whitespace characters.
Upvotes: 2