How to empty an element in vanilla JS
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.
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
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
Here’s the complete function:
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!