Select add()Method

Select 对象参考手册Select Object

Definition and Usage

The add() method is used to add an <option> element to a <select>.

Syntax

selectObject.add(option,before)

Parameter Description
option Required. The option element to be added. Must be an option or optgroup element.
before Required. Adds a new element before the specified element in the options array. If this parameter is null, the element is added to the end of the options array.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the add() method.

Tip:The add() method requires a <!DOCTYPE> declaration in IE8 and later versions of IE.


Example

Example

The following example adds a "kiwi" option to the end of the dropdown list:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rookie Tutorial (example.com)</title>
<script>
function displayResult(){
    var x=document.getElementById("mySelect");
    var option=document.createElement("option");
    option.text="Kiwi";
    try{
// For IE8 and earlier versions
        x.add(option,x.options[null]);
    }catch (e){
         x.add(option,null);
    }
}
</script>
</head>
<body>

<form>
<select id="mySelect">
    <option>Apple</option>
    <option>Pear</option>
    <option>Banana</option>
    <option>Orange</option>
</select>
</form>
<br>
<button type="button" onclick="displayResult()">Insert option</button>
<p><b>Note:</b> The add() method works normally in IE8 or higher; you should add a <!DOCTYPE> declaration in the page. For versions before IE8, also note the extra code.</p>
</body>
</html>

Try it Yourself »


实例

More Examples

Add an option before the selected option in the dropdown list


Select 对象参考手册Select Object Other extensions