javascript remove all child nodes javascript / jquery

JavaScript performance comparison

Revision 376 of this test case created by Alex Offshore

Preparation code

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

      
<script>
Benchmark.prototype.setup = function() {
  var container = document.body.appendChild(document.createElement('div')),
      range = document.createRange(),
      tpl = document.createElement('div');
  
  for (var i = 0; i < 5000; i++) {
      tpl.appendChild(document.createElement('b'));
      tpl.appendChild(document.createTextNode('asdf fewf'));
  }
  function makeBox() {
      while (container.lastChild) container.removeChild(container.lastChild);
      return container.appendChild(tpl.cloneNode(true));
  };
  makeBox(); // to make first iteration be in same conditions

};
</script>

Preparation code output

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
removeChild firstChild
var box = makeBox();
while (box.firstChild) box.removeChild(box.firstChild);
pending…
removeChild lastChild
var box = makeBox();
while (box.lastChild) box.removeChild(box.lastChild);
pending…
remove lastChild (non-wide)
var box = makeBox();
while (box.lastChild) box.lastChild.remove();
pending…
removeChild lastChild via hasChildNodes()
var box = makeBox();
while (box.hasChildNodes()) box.removeChild(box.lastChild);
pending…
range.deleteContents (IE9+)
var box = makeBox();
range.selectNodeContents(box);
range.deleteContents();
pending…
replaceChild cloneNode(false) (DESTRUCTIVE)
/**
* WARN
* While this approach seems legit and may be fastest,
* it can have some side effects on your environment.
*/
var box = makeBox();
var tmpBox = box.cloneNode(false);
box.parentNode.replaceChild(tmpBox, box);
box = tmpBox;
pending…
removeChild lastChild while detached
var box = makeBox(),
    parent = box.parentNode,
    next = box.nextSibling;
parent.removeChild(box);
while (box.lastChild) box.removeChild(box.lastChild);
parent.insertBefore(box, next);
pending…
removeChild lastChild while display = none
var box = makeBox(),
    display = box.style.display;
box.style.display = 'none';
while (box.hasChildNodes()) box.removeChild(box.lastChild);
box.style.display = display;
pending…
innerHTML
var box = makeBox();
box.innerHTML = '';
pending…
jQuery contents remove
var box = makeBox();
$(box).contents().remove();
pending…
jQuery empty
var box = makeBox();
$(box).empty();
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