Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. HTMLOptionElement
  4. Option()

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.

TheOption() constructor creates a newHTMLOptionElement.

Syntax

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

Parameters

textOptional

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

valueOptional

A string representing the value of theHTMLOptionElement, i.e., the value attribute of the equivalent<option>. If this is not specified, the value of text is used as thevalue, e.g., for the associated<select> element's value when the formis submitted to the server.

defaultSelectedOptional

A value of eithertrue orfalse that sets theselectedattribute value, i.e., so that this<option> will be the default valueselected in the<select> element when the page is first loaded. Ifthis is not specified, a default value of false is used. Note that a value of truedoes not set the option to selected if it is not already selected.

selectedOptional

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

Examples

Just add new options

js
/* assuming we have the following HTML<select id='s'></select>*/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

html
<select></select>
js
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); // Will actually be selected in the view  }});

Result:

html
<select>  <option value="0">zero</option>  <option value="1" selected>one</option>  <option value="2">two</option>  <!-- User will see two as 'selected' --></select>

Specifications

Specification
HTML
# dom-option-dev

Browser compatibility

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp