Is there a way to loop through the immediate children of an XML node in JavaScript, without using jquery or a similar library? I tried to use “.childNodes”, but for some reason it doesn’t work as it should. “.childNodes.length” return a number which is usually greater than the number of immediate nodes, and all of the tag names (using .tagName) are for some reason undefined. I know that my XML data is formated correctly because if I call “.getElementsByTagName()” using the tags of the immediate children, it works as it should.
Some examples of my dilemma :
var root = xmlData.getElementsByTagName("library_geometries")[0];
for (i = 0; i < root.childNodes.length; i++) //get all the geometries
{
geom = root.childNodes[i];
alert(geom.tagName);
}
------------------------------------------------------
geom = root.getElementsByTagName("geometry");
for (i = 0; i < geom.length; i++) //get all the geometries
{
alert(geom[i].tagName);
}
First one doesn’t work at all, second one works in this example.
This is actually a clarification of Hemlock’s answer. I’m putting it here instead of commenting his answer because I don’t have space to draw pretty ASCII art in comments.
Lets say we have the following XML:
This generates the following DOM:
which is generally what you’d expect.
Lets say we now have the following XML:
You would think this generates the same DOM. But according to the standard, you’d be wrong. Instead the standard requires it to generate the following DOM:
Yes, the spec says all those whitespace should be captured in the DOM. Almost all XML implementations out there does this (not only in browsers). The only exception being IE (and by extension the XML engine in JScript) because Microsoft didn’t care much about violating standards.
Personally this is useless 99.999% of the time. About the only time this would be useful is if you’re trying to implement an XML code editor. But it’s in the standards so browsers need to implement it if they want to be standards compliant.