XML DOM Mozilla vs. Internet Explorer
Browser-differences in DOM Parsing
Both Mozilla and Internet Explorer supports W3C's DOM specification.
However, there are still differences
between Internet Explorer's DOM and Mozilla's DOM. The most important difference is how
they handle white-space text nodes. When XML generates, it often contains white-spaces between
the nodes. Internet Explorer, when using node.childNodes[],
will NOT contain these white-space nodes. In Mozilla, those nodes will be in the
array.
Look at the following XML file:
books.xml
The following code fragment alerts how many child nodes the root element
have:
xmlDoc.load("books.xml");
var x=xmlDoc.documentElement.childNodes;
alert(x.length)
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeType);
document.write("<br />");
}
|
Try
it yourself
Internet Explorer will skip the white-space text nodes that are generated between
nodes (e.g. new line characters), while Mozilla will not. So, in the example
above, Mozilla browsers will alert 9 child nodes, while Internet Explorer will
alert 4.
To iterate through the child nodes and
disregard those text nodes, you can check the node type. An element node
has type 1, a text node has type 3, and a comment node has type 8. To skip
text nodes, you can process only nodes that are not of node type 3 (text nodes)
and node type 8 (comment nodes):
xmlDoc.load("books.xml");
var x=xmlDoc.documentElement.childNodes;
for (var i=0;i<x.length;i++)
{ if ((x[i].nodeType!=3)&&(x[i].nodeType!=8))
{
//Do not process text nodes or comment nodes document.write(x[i].nodeName);
document.write("<br />");
} }
|
Try it yourself
The best way to only process element nodes is to iterate through the child nodes
and only process those with a node type of 1:
xmlDoc.load("books.xml");
var x=xmlDoc.documentElement.childNodes;
for (var i=0;i<x.length;i++)
{
if (x[i].nodeType==1)
{
//Process only element nodes
document.write(x[i].nodeName);
document.write("<br />");
}
}
|
For a complete reference of all the node types and which children they may
have, go to our Node types reference.
|