I want to access the textContent property of an XML object in JavaScript. The root element has several children who also have some children. To get children at the first level, I just iterate over the childNodes array from the root element. But to get the values โโof the "grandchildren", I would like to use something like getElementsByTagName() , which does not work. Currently, I just iterate over all the children and check each nodeName property to get my values. Is there a way to get a child by name?
XML ( Note: The XML document I receive internally is unformatted, no spaces, no #text nodes ):
<root> <element> <child1>content</child1> <child2>content</child2> <child3>content</child3> </element> <element> <child1>content</child1> <child2>content</child2> <child3>content</child3> </element> </root>
What I have tried so far:
xmlDoc = xmlhttp.responseXML; for(i = 0; i < xmlDoc.documentElement.childNodes.length; i++) { key = xmlDoc.documentElement.childNodes[i]; alert(key.getElementsByTagName('child1')[0].textContent); }
which results in a message: undefined
and console error: TypeError: key.getElementsByTagName (...) [0] - undefined
Browser: Firefox 26
Perhaps this is a problem with the DOM object, I create it as follows:
var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc = xmlhttp.responseXML;
source share