Take a simple HTML code as an Example
<Div id = "Div">
<Div id = "div01"> This is div01 </div>
<Div id = "div02"> This is div02 </div>
</Div>
Childnodes: obtains all direct subnodes under a node.
VaR node = Document. getelementbyid ("Div"). childnodes; // obtain all subnodes under the DIV Node
At this time, if you alert the value from alert, you will find the problem.
Alert (node. Length );
If the browser you use is IE and IE <9, the value is 2.
If your browser is Google, FF, ie> = 9, the value is 5.
The reason for this difference is that IE (ie <9) has different mechanisms for processing blank text nodes from other browsers.
FF, Google, ie> = 9 the browser counts the gaps between nodes as one node, that is, there is a blank node between the outermost Div and div1, but IE (ie <9) no.
So how can we achieve compatibility with various browsers? I have two methods here.
The first method is to change the source code writing format.
<Div id = "Div"
> <Div id = "div01"> This is div01 </Div
> <Div id = "div02"> This is div02 </Div
> </Div>
Tested, all alert values are 2. However, this method looks awkward and troublesome to write. Many code labels are not easy to maintain.
The second method is to delete spaces before calling the childnodes attribute. The following is a method to delete spaces:
For (VAR I = 0; I <node. length; I ++ ){
// If it is a text node and the value is null, delete the node.
If (node [I]. nodetype = 3 &/\ s/. Test (node [I]. nodevalue )){
Node [I]. parentnode. removechild (node [I]);
}
}
Alert (node. Length );
In this way, the same effect can be achieved, and the HTML code format does not need to be changed.
PS: the essence of this for loop is to traverse all sub-nodes. If it is a text node and the value is empty, delete the node.
Node [I]. nodetype = 3 indicates determining whether a subnode is a text node.
Use childnodes in different browsers to obtain the number of subnodes