Home > Web Front-end > JS Tutorial > body text

JavaScript has traps: delete all nodes in a certain area_javascript skills

WBOY
Release: 2016-05-16 18:27:37
Original
920 people have browsed it

Relatively simple, for example: there is an area

, and now it is required to delete all nodes in it. I believe many people will write like this:

Copy code The 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 correct, traverse one by one, and finally delete them all. However, if you think about it carefully, every time a node is deleted, controlinfo.length will become smaller. If this continues, all nodes cannot be deleted - there is a bug. So how to improve? It is already very clear, since starting from the beginning is not possible, then we will start from the end, which is completely correct, 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]);
}

Debugging, Very Good!

This kind of trap is not only encountered in JavaScript, basically all languages, such as C#, Java, etc., we will encounter such problems, and sometimes we will waste a lot of time because of such problems. . I have known about this problem for a long time, but I always trust my memory too much and fail to record it properly. Now I record it to warn myself and share it with everyone.
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!