Remove all children of an element in JavaScript

The DOM API does not provide a function to remove all children of an element. A straightforward way to do this is to remove each child element:

function removeAllChildren(e) {
  while(e.firstChild) {
    e.removeChild(e.firstChild);
  }
}

This works, but there is a faster alternative: select all children using the DOM Range API and delete the contents of the range. This is supported in all modern browsers (in Internet Explorer since version 9).

function removeAllChildren(e) {
  var r = document.createRange();
  r.selectNodeContents(e);
  r.deleteContents();
  r.detach();
}

If you need backward compatibility with older browsers, you can check whether the range API is supported and use the old method otherwise:

var removeAllChildren = document.createRange
  ? function(e) {
    var r = document.createRange();
    r.selectNodeContents(e);
    r.deleteContents();
    r.detach();
  } : function(e) {
    while(e.firstChild) {
      e.removeChild(e.firstChild);
    }
  };