I need to get the the name of the tag "myChild" and the "content". This is simple, but i am stuck, sleepy and here is what I get with my tests:
XML:
...
<myParent>
<myChild>content</myChild>
</myParent>
<myParent>
<myChild>content</myChild>
</myParent>
...
JS:
var x=xmlDoc.getElementsByTagName("myParent");
alert(x[1].childNodes[0].nodeName); //returns "#text" - "myChild" needed
alert(x[1].childNodes[0].nodeValue); //returns "" - "content" needed
Try
x[1].getElementsByTagName('*')[0]
instead.(This is only trustable for index 0, other indexes may return elements that are not child-nodes, if the direct childs contain further element-nodes. )
You want(Sorry about that, fortagName
, which is the name of the element.Element
s,tagName
andnodeName
are the same.)The problem is that the first child of your
myParent
element isn't themyChild
element, it's a text node (containing whitespace). Your structure looks like this:You need to navigate down to the actual
myChild
element, which you can do withgetElementsByTagName
again, or just by scanning:Note that
Element
s don't have a meaningfulnodeValue
property; instead, you collect their child text nodes. (More in the DOM specs: DOM2, DOM3.)Also note that when indexing into a
NodeList
, the indexes start at0
. You seem to have started with1
; ignore this comment if you were skipping the first one for a reason.Off-topic: It's always best to understand the underlying mechanics of what you're working with, and I do recommend playing around with the straight DOM and referring to the DOM specs listed above. But for interacting with these trees, a good library can be really useful and save you a lot of time. jQuery works well with XML data. I haven't used any of the others like Prototype, YUI, Closure, or any of several others with XML, so can't speak to that, but I expect at least some of them support it.