Fastest method of clearing all children from a DOM element (v475)

Revision 475 of this benchmark created on


Preparation HTML

<div id="container"></div>

Setup

document.getElementById('container').innerHTML = '<div id="box"><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span><span>Abc123</span></div>';
  var box = document.getElementById('box');

Test runner

Ready to run.

Testing in
TestOps/sec
innerText = ''
box.innerText = '';
ready
removeChild(box.firstChild)
while (box.firstChild) {
  box.removeChild(box.firstChild);
}
ready
textContent = '';
box.textContent = '';
ready
removeChild(box.lastChild)
while (box.childNodes.length > 1) {
  box.removeChild(box.childNodes[box.childNodes.length - 2]);
}
box.removeChild(box.lastChild);
ready
cachedLastChild
let child;
while (child = box.lastChild) {
  box.removeChild(child);
}
ready
Never do it like this
let i,
		parent,
		children = box.childNodes,
		count = children.length;

	for (i = count - 1; i >= 0; i--) {
		parent = children[i].parentNode;

		if (parent) {
			parent.removeChild(children[i]);
		}
	}
ready
innerHTML = ''
box.innerHTML = '';
ready
removeChild(box.lastChild)
while (box.lastChild) {
  box.removeChild(box.lastChild);
}
ready
cloneNode(false)
box.replaceWith(box.cloneNode(false));
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.