Article Introduction: the childnodes difference between IE and Firefox!! |
JavaScript, I believe that we have tried to use getElementsByTagName and childnodes to achieve the traversal of the node. But getelementsbytagname to complex DOM structure traversal is obviously not as good as using childnodes, because ChildNodes can better deal with the hierarchy of the DOM, it is recommended that the traversal should be used first childnodes!!
Unfortunately, there is a slight difference in childnodes between IE and Firefox:
Function view () {
var childs1=$ (' Firstdiv '). ChildNodes;
var childs2=$ (' Seconddiv '). ChildNodes;
Alert ("Length of Firstdiv:" +childs1.length+ "--length of Seconddiv:" +childs2.length);
}
var $=function (ID)
{return document.getElementById (ID);}
</script>
<body onload= "view ();" >
<!--the first traversal object, leaving spaces between the nodes and carriage return-->
<div id= "Firstdiv" >
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<!--the second traversal object, except the annotation, between the nodes without space carriage return-->
<div id= "Seconddiv" ><div>first</div><div>second</div><div>third</div> </div>
Running with IE and Firefox will have two different results: IE results in 3:3, while Firefox is 7:3. How could this happen?
On the structure, object 1 and Object 2 are different from the child nodes of object 1 having carriage returns or spaces, and object 2 is a line written to the end. Everyone should think of it, IE is a complete label as a node. and Firefox in addition to the above situation, but also a label of The Terminator ">" to the next label "<" between the content (except the annotation, including any text, space, carriage return, tab) is a node. And such nodes also have their own unique attributes and values--nodename= "#text".
In practical use, Firefox when traversing the child nodes, in the For loop may wish to add:
if (childnode.nodename== "#text") continue;
or NodeType = 1.
This way, you skip unwanted operations and make the program more efficient.
Report:
- Node.element_node = 1
- Node.attribute_node = 2
- Node.text_node = 3
- Node.cdata_section_node = 4
- Node.entity_reference_node = 5
- Node.entity_node = 6
- Node.processing_instruction_node = 7
- Node.comment_node = 8
- Node.document_node = 9
- Node.document_type_node = 10
- Node.document_fragment_node = 11
- Node.notation_node = 12
Cases
var node = Document.documentElement.firstChild;
if (Node.nodetype!= node.comment_node)
Alert ("You should comment your code well!");