MDN self-hosted library · e01.org

HTMLOptionElement: Option() constructor

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

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);
});
html
<select id="s"></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
  }
});
html
<select id="s">
  <option value="0">zero</option>
  <option value="1" selected>one</option>
  <option value="2">two</option>
  <!-- User will see two as 'selected' -->
</select>