Home > Web Front-end > JS Tutorial > The difference between childNodes in IE and FireFox_javascript skills

The difference between childNodes in IE and FireFox_javascript skills

WBOY
Release: 2016-05-16 18:00:46
Original
1143 people have browsed it

In Javascript, I believe everyone has tried using getElementsByTagName and childNodes to traverse nodes. However, getElementsByTagName is obviously not as good as using childNodes for complex DOM structure traversal, because childNodes can better handle the DOM hierarchy. It is recommended to use childNodes first when traversal is needed!!
But unfortunately, in IE and FireFox, The childNodes are slightly different:

Copy code The code is as follows:

< script type="text/javascript">
function view(){
var childs1=$('FirstDiv').childNodes;
var childs2=$('SecondDiv').childNodes;
alert("length of FirstDiv: " children1.length "--length of SecondDiv: " children2.length);
}
var $=function(id)
{ return document.getElementById(id) ; }






1


3



first
second
third




Running with IE and Firefox will have two different results: IE’s result is 3:3; while Firefox’s is 7:3. How could this happen?
Structurally, the difference between object 1 and object 2 is that there are carriage returns or spaces between the child nodes of object 1, while object 2 is written to the end in one line. Everyone should have thought of it, IE treats a complete label as a node. In addition to the above situations, Firefox also converts the content between the end character ">" of one label and the starting character "<" of the next label (except comments, including any text, spaces, and carriage returns). , tab) is also considered a node. And such nodes also have their own unique properties and values ​​- nodeName="#text".
In actual application, when Firefox is traversing child nodes, you may wish to add:
if(childNode.nodeName=="#text") continue;
or nodeType == 1 in the for loop.
In this way, unnecessary operations are skipped and the program runs more efficiently.
Attachment:
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

var node = document.documentElement.firstChild;
if(node.nodeType != Node.COMMENT_NODE) ​​
alert("You should comment your code well!");
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template