Adding and Removing Options in a Select Box
There are a variety of approaches for adding and removing option elements in a select box using JavaScript. An old-fashioned approach uses an option constructor and array syntax. Both select and options objects provide add and remove methods. But the focus here is on DOM methods due to their solid browser support and flexibility.
Add Option Using DOM Methods
The document.createElement
method is used to create an option element. The document.createTextNode
method is used to add text to the option. To add a value attribute to the option element, you can use either the setAttribute
method or dot syntax. To add the new option element to the end of the list of options, use the appendChild
method.
// get reference to select element
var sel = document.getElementById('selDemo');
// create new option element
var opt = document.createElement('option');
// create text node to add to option element (opt)
opt.appendChild( document.createTextNode('New Option Text') );
// set value property of opt
opt.value = 'option value';
// add opt to end of select box (sel)
sel.appendChild(opt);
Remove Option with removeChild
The removeChild
method can be used to remove an option or optgroup element from a select box:
// remove 2nd option in select box (sel)
sel.removeChild( sel.options[1] );