How would I go about removing all of the child elements of a DOM node in JavaScript?
Say I have the following (ugly) HTML:
&
element.innerHTML = ""
(or .textContent) is by far the fastest solution
For example:
https://jsperf.com/innerhtml-vs-removechild/15
This test does not add new children to the element between each iteration. The first iteration will remove the element's contents, and every other iteration will then do nothing.
In this case, while (box.lastChild) box.removeChild(box.lastChild)
was faster because box.lastChild was null
99% of the time
Here is a proper test: https://jsperf.com/innerhtml-conspiracy
Finally, do not use node.parentNode.replaceChild(node.cloneNode(false), node)
. This will replace the node with a copy of itself without its children. However, this does not preserve event listeners and breaks any other references to the node.