Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - Does removeChild really delete the element?

Does removeChild function really delete the child node completely? Or it just removes the element being child of the specified parant node? If it doesn't really deletes the element, is there a way to delete the element completely?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The removeChild method simply removes it from its parent. If it’s a visible element of the page, it will be removed from the page.

But Javascript has garbage collection. This means that the node object itself will remain in existence as long as any variable refers to it. So you can assign a node to a variable, use removeChild to 'prune' it from its parent node, and later on, insert or append it to some other node, thereby effectively moving it around on the page.

The following code will remove a node, and wait 10 seconds before re-adding it to the tree (and thus, to the page):

var oldNode = someNode.removeChild(...);
setTimeout(function () {
  document.documentElement.appendChild(oldNode);
}, 10000);

This means that the node object hasn’t been deleted from memory, because there’s still a variable pointing to it (namely, oldNode).

Another case:

var node = document.getElementById('test');
// ... do stuff
node.parentElement.removeChild(node);
// 'node' still exists, but has been removed from the page
// ... do some more stuff
node = document.getElementById('hello');
// The variable 'node' now points to something else; 
//  this means the original node will be deleted from memory

If, on the other hand, you don’t reassign the removed node to another variable, it can’t be accessed anymore (not via the document tree, since it’s been removed from there; and not via a JS variable); so Javascript will automatically purge it from memory:

someNode.removeChild(...);

Assigning the removed node to a variable, and then assigning null (or anything else) to that variable — like Marc B suggests in his answer — is completely unnecessary and, IMHO, silly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...