Reputation: 5259
To better understand the difference between textConent and nodeValue I'd like to find out why using nodeValue in my code is not working. I have the following XML string which gets loaded through AJAX via a jQuery callback. If you look at the center of the loop, that section will produce a null value if I use nodeValue in place of textContent.
XML
<?xml version="1.0" encoding="UTF-8"?>
<Sensors>
<Sensor>
<id>56</id>
<state>false</state>
</Sensor>
</Sensors>
I use this function below to parse the XML.
JavaScript
function parseSensors(data,status,xhr) {
var xml = xhr.responseXML;
var sensors = xml.documentElement.childNodes;
var list="<ul>";
for(var i=0; i < sensors.length; i++) {
list= list +"<li>"+sensors[i].childNodes[0].textContent+"</li>";
}
list=list+"</u>";
document.getElementById("real-time_active_sensors").innerHTML=list;
}
Upvotes: 3
Views: 2077
Reputation: 5259
The text portion of a node is actually a child of the node itself. If a node has no data in it, such as then a call to childNodes[0].nodeValue will fail. You need to check for how many childNodes are actually present before you attempt to access them. Otherwise you'll need to enforce a protocol that demands that when XML data is created it cannot contain empty tags.
Upvotes: 1