javascript remove all child nodes javascript / jquery

JavaScript performance comparison

Revision 219 of this test case created by

Preparation code

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

<script>
var boxAnchor = document.createElement('div');
boxAnchor.style.cssText="white-space:nowrap";
boxAnchor.id = 'box';
for(var i=0;i<1000;i++)
{
boxAnchor.appendChild(document.createElement('B').insertBefore(document.createTextNode('asdf fewf')).parentNode);
}
var box=document.getElementById('box');
function refreshRange()
{
box.parentNode.replaceChild(boxAnchor.cloneNode(true),box);
box=document.getElementById('box');
}
refreshRange();
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

    

Preparation code output

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

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
innerHTML hide
refreshRange();
box.hidden = true;
box.innerHTML = '';
box.hidden = false;
pending…
hide hide
refreshRange();
box.hidden = true;
while(box.hasChildNodes())
  box.removeChild(box.firstChild);
box.hidden = false;
pending…
removeChild Recheck
refreshRange();
while (box.firstChild) 
  box.removeChild(box.firstChild);
pending…
removeChild lastChild with reference
refreshRange();
    var last;
    while ((last = box.lastChild)) box.removeChild(last);
pending…
firstChild haschildnodes() check
refreshRange();
while(box.hasChildNodes())
  box.removeChild(box.firstChild);
pending…
deletecontents (IE9+)
refreshRange();
var range = document.createRange();
range.selectNodeContents(box);
range.deleteContents();
pending…
replaceChild cloneNode(shallow) (DESTRUCTIVE)
refreshRange();
var newBox = box.cloneNode(false);
box.parentNode.replaceChild(newBox,box);
box=newBox;
pending…
removeChild then reAttach
refreshRange();
var parent = box.parentNode;
var next = box.nextSibling;
parent.removeChild(box);
while(box.hasChildNodes())
  box.removeChild(box.firstChild);
parent.insertBefore(box,next);
pending…
innerhtml = ""
refreshRange();
box.innerHTML = '';
pending…
jquery
refreshRange();
$(box).contents().remove();
pending…
hide
refreshRange();
var display = box.style.display;
box.style.display = 'none';
while(box.hasChildNodes())
  box.removeChild(box.firstChild);
box.style.display = display;
pending…

Compare results of other browsers

Revisions

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

0 Comments