Demo: Add/Remove Options with DOM Methods

Earlier we discussed the benefits and basics of using DOM methods for adding and removing option elements in select boxes. Here we provide convenience functions that use these methods.

The addOptionToSelect function can append or insert options, specifying either index or element reference for inserting. This function includes the capability to append to an optgroup, specifying either its index in the optgroups collection or its label. Functions are also provided for removing option and optgroup elements from select boxes. These functions are displayed below.

The following form demonstrates. The information provided in parentheses beside the buttons indicates which of the features described above are being demonstrated.

Demo: Add/Remove Options

(index: 0)

(label: Group 2)

(reference: sel.options[2])

(index: 2)

(index: 1)

(reference: sel.options[1])

(index: 0)

(label: Group 2)

Functions to Add/Remove Options

The addOptionToSelect, removeOption, and removeAllOptions functions are displayed here:

/** addOptionToSelect arguments:
  *   sel: reference to select box
  *   txt: option text
  *   val: (optional) option value
  *   obj: (optional) object to hold either idx, el, grp or lbl
  *        to specify where the new option element should be inserted
  *        Examples for obj: {idx: 2} to insert before 3rd option
  *            {el: sel.options[2]} to insert before sel.options[2]
  *            {grp: 0} append to first optgroup
  *            {lbl: 'Group 2'} append to optgroup with label: 'Group 2'
  */
function addOptionToSelect(sel, txt, val, obj) {
    var opt = document.createElement('option');
    opt.appendChild( document.createTextNode(txt) );
    
    if ( typeof val === 'string' ) {
        opt.value = val;
    }
    
    if ( !obj ) {
        sel.appendChild(opt);
        return;
    }
    
    var group;
    var el = (typeof obj.el === 'object')? obj.el: (typeof obj.idx === 'number')? sel.options[ obj.idx ]: null;
    
    if (el) {
        // not sel.insertBefore in case optgroup contains
        el.parentNode.insertBefore(opt, el);
        return;
    }
    
    var groups = sel.getElementsByTagName('optgroup');
    
    if ( typeof obj.grp === 'number' ) {
        group = groups[ obj.grp ];
    } else if ( typeof obj.lbl === 'string' ) {
        
        for (var i=0, len=groups.length; i<len; i++) {
            if ( groups[i].label === obj.lbl ) {
                group = groups[i];
                break;
            }
        }
    }
    
    if ( group ) {
        group.appendChild(opt);
    }
    return;
}

// removes all option elements in select box 
// removeGrp (optional) boolean to remove optgroups
function removeAllOptions(sel, removeGrp) {
    var len, groups, par;
    if (removeGrp) {
        groups = sel.getElementsByTagName('optgroup');
        len = groups.length;
        for (var i=len; i; i--) {
            sel.removeChild( groups[i-1] );
        }
        
    }
    
    len = sel.options.length;
    for (var i=len; i; i--) {
        par = sel.options[i-1].parentNode;
        par.removeChild( sel.options[i-1] );
    }
}

// opt is element ref or index
function removeOption(sel, opt) {
    var el = (typeof opt === 'object')? opt: (typeof opt === 'number')? sel.options[ opt ]: null;
    
    if (el) {
        // not sel.removeChild in case optgroup contains
        el.parentNode.removeChild(el);
    }
    
}

// grp is index or label
function removeOptGroup(sel, grp) {
    var group;
    var groups = sel.getElementsByTagName('optgroup');
    
    if ( typeof grp === 'number' ) {
        group = groups[ grp ];
    } else if ( typeof grp === 'string' ) {
        
        for (var i=0, len=groups.length; i<len; i++) {
            if ( groups[i].label === grp ) {
                group = groups[i];
                break;
            }
        }
    }
    
    if ( group ) {
        sel.removeChild(group);
    }
    
}

Using the addOptionToSelect Function

You can use the addOptionToSelect function to add a new option element to the end of the existing list of options as follows:

var sel = document.getElementById('selDemo');
// add new option at end of existing list of options 
addOptionToSelect(sel, 'New Option');

The addOptionToSelect function also provides the capability to insert new option elements elsewhere among the collection. The following gives more details.

// Example addOptionToSelect function calls:

// add new option at end of first optgroup using index to specify
addOptionToSelect(sel, 'New Option', null, {grp: 0} );

// add new option at end of first optgroup using label to indicate which optgroup
addOptionToSelect(sel, 'New Option', null, {lbl: 'Group 2'} );

// insert new option specifying location using index
addOptionToSelect(sel, 'Before 3rd Option', null, {idx: 2} );

// insert new option specifying element reference before which to place it
addOptionToSelect(sel, 'Before Option 3', null, {el: sel.options[2]} );

Using the Remove Functions

You can remove an option element using the removeOption function, passing either its index or an element reference as the second argument. Pass a reference to the select box for the first argument with each of these functions.

// remove option specifying its index in the collection
removeOption(sel, 1);

// remove option passing reference to it
removeOption(sel, sel.options[1] );

To remove an optgroup use the function removeOptGroup, passing either its index or label.

// remove optgroup specifying its index
removeOptGroup(sel, 0);

// remove optgroup specifying its label
removeOptGroup(sel, 'Group 2');

To remove all options from a select box, use the removeAllOptions function. Pass true as the second argument to the function to also remove all optgroups from a select box.

// remove all options
// 2nd argument specifies whether you would also like to remove all optgroups
removeAllOptions(sel, true);

This example is included in a download file.

Back to top