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
2
3
4
5
6
7
<!-- other form elements -->
<select name="whatever" id="somemenu">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<!-- 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
2
3
4
5
var dropdown = document.getElementById('somemenu');
while(dropdown.hasChildNodes())
{
    dropdown.removeChild(dropdown.lastChild);
}

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.

Related Posts:

  • No Related Posts

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">