Lori
Lori

Reputation: 1422

Does node.removeChild(node.firstChild) create a memory leak?

MDN says this is one way to remove all children from a node. But since only the first child node is referenced in code, do the others become memory orphans? Is anything known about whether this is the case in any or all browsers? Is there something in the DOM standard that calls for garbage collection when doing this?

Upvotes: 0

Views: 100

Answers (1)

toskv
toskv

Reputation: 31600

I guess you are referring to this example

// This is one way to remove all children from a node
// box is an object reference to an element with children

while (box.firstChild) {
  //The list is LIVE so it will re-index each call
  box.removeChild(box.firstChild);
}

No it does not cause a memory leak. What happens is after the 1st child is removed the 2nd one will take it's place as the 1st child, and so on until there are no more children left.

Also garbage collection can not be usually requested on demand, the virtual machine will do it when it thinks it can, and that does differ between browsers.

Upvotes: 3

Related Questions