I want to access the textContent property of an XML object in JavaScript. The root item has several children which also have some children themselves. To get the children on
The problem is the spaces between the nodes are automatically made textNodes. Check if the node at xmlDoc.documentElement.childNodes[i]
is a textNode
(nodeType 3) before you try to find children. I also removed your globals i
and key
in this example.
http://jsfiddle.net/GQ8Kd/
var node, childNodes = xmlDoc.documentElement.childNodes;
for(var i = 0; i < childNodes.length; i++)
{
node = childNodes[i];
if(node.nodeType !== Node.TEXT_NODE) console.log(node.getElementsByTagName('child1')[0].textContent);
}
Using the following obtains the desired value of the child1 nodes for me..
var k = xmlDoc.getElementsByTagName("child1");
for(var i = 0; i < k.length; i++)
{
console.log(k[i].childNodes[0].nodeValue);
}
Try getElementsByTagName('child1')[0].nodeValue