Deleting Child Nodes of an Element Using JavaScript and the DOM

A common thing to want to do with JavaScript and the DOM is to delete all child elements within a parent element. This could be a table, ordered/unordered list, or select menu. Unfortunately it seems that doing this is a PITA judging by how many people have posted requests for help throughout the Internet.

Here is the code I found worked best for me. Here’s the HTML of a <select> element that we want to remove all of the <option> tags for.

  1. <!-- other form elements -->
  2. <select name="whatever" id="somemenu">
  3.     <option value="1">1</option>
  4.     <option value="2">2</option>
  5.     <option value="3">3</option>
  6. </select>
  7. <!-- other form elements -->

To remove all of the <option> tags we would call the following JavaScript. It most likely would be in a function:

  1. var dropdown = document.getElementById('somemenu');
  2. while(dropdown.hasChildNodes()) {
  3.     dropdown.removeChild(dropdown.lastChild);
  4. }

Naturally it is your responsibility to repopulate the <select> element in this case. But if you need an element emptied of its children, this code snippet should do it.

Leave a Reply

Your email address will not be published. Required fields are marked *