Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textContent working but nodeValue does not

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;            
     }
like image 947
Usman Mutawakil Avatar asked May 17 '26 03:05

Usman Mutawakil


1 Answers

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.

like image 55
Usman Mutawakil Avatar answered May 18 '26 15:05

Usman Mutawakil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!