JavaScript exists trap remove all nodes in a region _javascript tips

Source: Internet
Author: User
Relatively simple, for example: There is a region <div id= "Newbody" ></div&gt, and now requires that all nodes be deleted. I believe many people will write this:
Copy Code code as follows:

var Divpanel = document.getElementById ("Newbody");
var controlinfo= divpanel.childnodes;
for (var index = 0;index < controlinfo.length; index++)
{
Divpanel.removechild (Controlinfo[index]);
}

I see, yes ah, yes, this is true ah, one traversal, and finally all deleted. But, think about it, every time you delete a node, the controlinfo.length becomes smaller, so you can't delete it all-there are bugs. So how to improve it? It's already clear that since the start start doesn't work, we start at the end, completely right, as follows:
Copy Code code as follows:

var Divpanel = document.getElementById ("Newbody");
var controlinfo= divpanel.childnodes;
for (var index = controlinfo.length-1;index >= 0; index--)
{
Divpanel.removechild (Controlinfo[index]);
}

Commissioning, Very good!

This trap is not only encountered in JavaScript, basically all languages, such as C #, Java and so on, we will encounter such problems, sometimes because of such a problem and waste a lot of time. Already knew this question very early, but always too believed own memory, but did not have the good record, now the special record, warns oneself, simultaneously also shares with everybody.
Related Article

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.