tags:

views:

20

answers:

2

hello,

i am parsing a XML string to an XML Document in Javascript. The xml structure might look like this:

 <parent>
     <parent2>
        <x>
           <y1/>
           <xyz>
               <tra/>
           <xyz>
           <y2/>
        </x>
        <x>
           <y1/>
        </x>
        ..
     </parent2>
 </parent>

Now i want to iterate through x .. I did all the time with getElementsByTagName() but if i want to get a node inside x i am using this function twice and this doensnot work:

var cX=xmldoc.getElementsByTagName('x');
alert(cX.getElementsByTagName('tra')[0].innerHTML)

So how i can solve the problem? the name and position of x is even fixed and might not change. But the content inside x can change in its structure. And so i would like to use the getElementsByTagName() because i haven't to know the exakt position in tree! But how to use getElementsByTagName() nested?

Thanks for your help!

Update: Everything works fine for XML too! for example: alert(xmldoc.getElementsByTagName('x')[2].getElementsByTagName('tra')[0].firstChild.nodeValue); Thanks for the help!

A: 

The getElementsByTagName function does not return an XML document. It returns an array of elements. Therefore, you cannot call The getElementsByTagName function again.

Gabriel McAdams
this is not correct (i thought the same like you)! you can call the function twice and get a result!
rokdd
The only reason you can call it again is that in some implementations of JavaScript, when you have an array with only one item in it, it lets you operate on the array directly (array.something) instead of accessing the first item in the array (array[0].something). It is never safe to do this, because you never know what is in the array. There may be more than one item - or you may be in a system that doesn't allow this. Either way, your code would break.
Gabriel McAdams
A: 

Everything works fine with XML Document too! for example: alert(xmldoc.getElementsByTagName('x')[2].getElementsByTagName('tra')[0].firstChild.nodeValue);

rokdd