HTMLOptionElement: Option() constructor

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

The Option() constructor creates a new HTMLOptionElement.

Syntax

js
new Option()
new Option(text)
new Option(text, value)
new Option(text, value, defaultSelected)
new Option(text, value, defaultSelected, selected)

Parameters

text Optional

A string representing the content of the element, i.e., the displayed text. If this is not specified, a default value of "" (empty string) is used.

value Optional

A string representing the value of the HTMLOptionElement, i.e., the value attribute of the equivalent . If this is not specified, the value of text is used as the value, e.g., for the associated element when the page is first loaded. If this is not specified, a default value of false is used. Note that a value of true does not set the option to selected if it is not already selected.

selected Optional

A value of either true or false that sets the option's selected state; the default is false (not selected). If omitted, even if the defaultSelected argument is true, the option is not selected.

Examples

Just add new options

js
/* assuming we have the following HTML

*/

const s = document.getElementById("s");
const options = [Four, Five, Six];

options.forEach((element, key) => {
  s[key] = new Option(element, key);
});

Append options with different parameters

js
/* assuming we have the following HTML

*/

const s = document.getElementById("s");
const options = ["zero", "one", "two"];

options.forEach((element, key) => {
  if (element === "zero") {
    s[key] = new Option(element, s.options.length, false, false);
  }
  if (element === "one") {
    s[key] = new Option(element, s.options.length, true, false); // Will add the "selected" attribute
  }
  if (element === "two") {
    s[key] = new Option(element, s.options.length, false, true); // Just will be selected in "view"
  }
});

/* Result

*/

Specifications

Specification
HTML
# dom-option-dev

Browser compatibility