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];
al开发者_如何学运维ert(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:
<a><b></b><c></c></a>
This generates the following DOM:
<a>--.
|
<b>
|
<c>
which is generally what you'd expect.
Lets say we now have the following XML:
<a>
<b></b>
<c></c>
</a>
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:
<a>--.
|
"\n "
|
<b>
|
"\n "
|
<c>
|
"\n"
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.
You are getting text nodes (nodeType == 3) mixed in with elements. The text nodes probably only contain white space. You just want to filter your loop on nodeType (like Pointy said).
var root = xmlData.getElementsByTagName("library_geometries")[0];
for (i = 0; i < root.childNodes.length; i++) //get all the geometries
{
geom = root.childNodes[i];
if (geom.nodeType == 1) {
alert(geom.tagName);
}
}
https://developer.mozilla.org/en/nodeType
Wait the html document to be parsed. You should run this piece of script when the document is ready, in onload() the document is not parsed yet so it`s possible you wont find tags.
精彩评论