Bisexual Pride

In jQuery, we can remove all child nodes from an element using the empty() method. Let’s create a helper function for this using only vanilla JS.

Disclaimer: you absolutely could just set an element’s innerHTML property to a blank string. This is just another approach I felt like writing about. Thanks for reminding me to add this, James Doc!

First, let’s define our function. It accepts a single argument, element, which is the element we want to empty.

/**
* Remove all child nodes from an element
* @param {Object} element The element to empty
*/

function empty (element) {
// Do stuff
}

Next, we’ll get the element’s child nodes as an array. We can get the child nodes using the element’s childNodes property. This returns a NodeList, though, and we want an array for better browser support. Let’s convert the NodeList to an array using the Array.prototype.slice.call() trick:

// Get the element's children as an array
var children = Array.prototype.slice.call(element.childNodes);

Finally, we can loop through the array using the Array.forEach() method, removing each child node as we go. We can do this using the Node.removeChild() method.

// Remove each child node
children.forEach(function (child) {
element.removeChild(child);
});

Here’s the complete function:

/**
* Remove all child nodes from an element
* @param {Object} element The element to empty
*/

function empty (element) {

// Get the element's children as an array
var children = Array.prototype.slice.call(element.childNodes);

// Remove each child node
children.forEach(function (child) {
element.removeChild(child);
});

}

For more vanilla JS helper functions, check out The Vanilla JS Toolkit. It’s an awesome resource my friend Chris Ferdinandi maintains.