JavaScript traps exist to delete all nodes in a region

Source: Internet
Author: User

For example, if you have a region <div id = "newbody"> </div>, delete all nodes. I believe many people will write like this:
Copy codeThe Code is as follows:
Var divpanel = document. getElementById ("newbody ");
Var controlinfo = divpanel. childNodes;
For (var index = 0; index <controlinfo. length; index ++)
{
Divpanel. removeChild (controlinfo [index]);
}

At first glance, yes, yes. This is very correct. traverse one by one and delete all at last. However, when you delete a node, the value of controlinfo. length will decrease. In this case, you cannot delete all nodes. A Bug exists. So how can we improve it? It is clear that starting from the beginning does not work, so we Start from the end, which is completely correct, as shown below:
Copy codeThe Code is as follows:
Var divpanel = document. getElementById ("newbody ");
Var controlinfo = divpanel. childNodes;
For (var index = controlinfo. length-1; index> = 0; index --)
{
Divpanel. removeChild (controlinfo [index]);
}

Debug, Very Good!

This kind of trap is not only encountered in JavaScript. Basically all languages, such as C # and Java, will encounter such problems, sometimes time is wasted due to such problems. I have known this problem for a long time, but I always believe in my memory, but I have not recorded it well. Now I want to record it, warn myself, and share it with you.

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.