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.
Tags: document object model, javascript
June 30th, 2008 at 8:08 am | Posted in Programming