Over a million developers have joined DZone.

HTML/JavaScript - Select List - Add/Remove Options (DOM)

DZone's Guide to

HTML/JavaScript - Select List - Add/Remove Options (DOM)

· ·
Free Resource
from http://www.mredkj.com/tutorials/tutorial005.html


    * Insert Before Selected - A new option is created and added above the selected option (as determined by selectedIndex). If none are selected, then no option is added.
    * Remove Selected - Deletes the selected option (or options) from the list. If no options are selected, no options are deleted.
    * Append Last - No matter what is selected, a new option is added at the end.
    * Remove Last - No matter what is selected, the last option is deleted from the list.


According to DOM Level 1, the following is the syntax for the add and remove methods in HTMLSelectElement:

void add(in HTMLElement element, in HTMLElement before) raises(DOMException);
void remove(in long index);

The add method takes two arguments: the element to add, and the element to insert before. The spec also says you can add to the end of the list by passing null as the second argument.

The remove method just takes a number: the index of the option to be removed. 

The JavaScript


Insert Before Selected
Remove Selected

Append Last
Remove Last

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}