Home  >  Article  >  Web Front-end  >  Precautions for using javascript removeChild_javascript tips

Precautions for using javascript removeChild_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:54:23958browse

Suppose: a piece of ordinary code:
where gift_list is the id of a table

Copy code The code is as follows:

var giftBody = document.getElementById("gift_list").getElementsByTagName("tbody")[0];
var giftTrs = giftBody.getElementsByTagName("tr");
for (var i= 0;i{
giftTrs[i].removeChild(giftTrs[i]);
}

Then only the first child will be deleted at this time One row, because when one is deleted, the position of the row will move forward one position.
giftTrs.length will also be reduced by one accordingly.
So the correct operation method is:
Copy the code The code is as follows:

var giftBody = document.getElementById("gift_list").getElementsByTagName("tbody")[0];
var giftTrs = giftBody.getElementsByTagName("tr");
var len = giftTrs.length; //Need to change giftTrs The length attribute of .length is stored
for (var i=0;i{
giftBody.removeChild(giftTrs[0]);
}
Statement:
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