textContent working but nodeValue does not

孤者浪人 提交于 2019-12-12 14:08:20

问题


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;            
     }

回答1:


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.



来源:https://stackoverflow.com/questions/12718945/textcontent-working-but-nodevalue-does-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!