Use childnodes in different browsers to obtain the number of subnodes

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.