javascript remove all child nodes javascript / jquery (v484)

Revision 484 of this benchmark created by Michael Rawlings on


Preparation HTML

<div id="box"></div>

<script>
var boxAnchor, box, i, b, range;

boxAnchor = document.createElement('div');
boxAnchor.style.cssText="white-space:nowrap";
boxAnchor.id = 'box';

for (i = 0; i < 1000; i++) {
	b = document.createElement('B');
	b.appendChild(document.createTextNode('asdf fewf'));
	boxAnchor.appendChild(b);
}
box = document.getElementById('box');

// Clone boxAnchor to box
function refreshRange() {
	var newBox = boxAnchor.cloneNode(true);
	box.parentNode.replaceChild(newBox, box);
	box = newBox;
}

var range = document.createRange();

</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

refreshRange();

Test runner

Ready to run.

Testing in
TestOps/sec
innerhtml = ""
box.innerHTML = '';
ready
removeChild then reAttach
var parent = box.parentNode;
var next = box.nextSibling;
parent.removeChild(box);
while(box.hasChildNodes())
  box.removeChild(box.firstChild);
parent.insertBefore(box, next);
ready
replaceChild cloneNode(shallow) (DESTRUCTIVE)
var newBox = box.cloneNode(false);
box.parentNode.replaceChild(newBox, box);
box=newBox;
ready
hide
var display = box.style.display;
box.style.display = 'none';
while(box.hasChildNodes())
  box.removeChild(box.firstChild);
box.style.display = display;
ready
removeChild Recheck
while (box.firstChild) 
  box.removeChild(box.firstChild);
ready
jquery
$(box).contents().remove();
ready
firstChild haschildnodes() check
while(box.hasChildNodes())
  box.removeChild(box.firstChild);
ready
deletecontents (IE9+)
range.selectNodeContents(box);
range.deleteContents();
ready
removeChild lastChild with reference
var last;
while ((last = box.lastChild)) box.removeChild(last);
ready

Revisions

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