JavaScript: empty a DOM element

JavaScript: empty a DOM element

How to remove all the child nodes from a DOM element with JavaScript.

jQuery provides the empty() method to remove all child nodes from a given DOM element. Without jQuery, we have only two feasible options with JavaScript: innerHTML or removeChild. In this article I'll cover with more details the latter approach, since the former is really simple.

Here's our implementation:

HTMLElement.prototype.empty = function() {
    var that = this;
    while (that.hasChildNodes()) {
        that.removeChild(that.lastChild);
    }
};

The while loop ends only when there are no more child nodes available. Every time the loop runs, the last child of the element is removed. This behavior is similar to the action of the pop() method on arrays. At the end of the loop there will be no more child nodes to remove.

An example:

var empty = document.getElementById('empty'),
    test = document.getElementById('test');

empty.onclick = function() {
    test.empty();
}​

If you want to use innerHTML, the solution is absolutely straightforward:

HTMLElement.prototype.empty = function() {
	this.innerHTML = '';
}

This solution is much faster than the previous one. You can see the demo below.

Demo

Live demo