HTMLSelectElement: add() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

HTMLSelectElement.add() 方法將一個元素新增到此 select 元素的 option 元素集合中。

語法

js
add(item)
add(item, before)

引數

item

一個 HTMLOptionElementHTMLOptGroupElement

before 可選

集合中的一個元素,或一個型別為long的索引,表示item應該插入在其之前。如果此引數為 null(或索引不存在),則新元素將被新增到集合的末尾。

返回值

無(undefined)。

異常

HierarchyRequestError DOMException

如果傳遞給方法的itemHTMLSelectElement 的祖先,則會丟擲該錯誤。

示例

從頭開始建立元素

js
const sel = document.createElement("select");
const opt1 = document.createElement("option");
const opt2 = document.createElement("option");

opt1.value = "1";
opt1.text = "Option: Value 1";

opt2.value = "2";
opt2.text = "Option: Value 2";

sel.add(opt1, null);
sel.add(opt2, null);

/*
  Produces the following, conceptually:

  <select>
    <option value="1">Option: Value 1</option>
    <option value="2">Option: Value 2</option>
  </select>
*/

before 引數是可選的。因此,以下內容是被接受的。

js
sel.add(opt1);
sel.add(opt2);

新增到現有集合

js
const sel = document.getElementById("existingList");

const opt = document.createElement("option");
opt.value = "3";
opt.text = "Option: Value 3";

sel.add(opt, null);

/*
  Takes the existing following select object:

  <select id="existingList">
    <option value="1">Option: Value 1</option>
    <option value="2">Option: Value 2</option>
  </select>

  And changes it to:

  <select id="existingList">
    <option value="1">Option: Value 1</option>
    <option value="2">Option: Value 2</option>
    <option value="3">Option: Value 3</option>
  </select>
*/

before 引數是可選的。因此,以下內容是被接受的。

js
sel.add(opt);

插入到現有集合

js
const sel = document.getElementById("existingList");

const opt = document.createElement("option");
opt.value = "3";
opt.text = "Option: Value 3";

sel.add(opt, sel.options[1]);

/*
  Takes the existing following select object:

  <select id="existingList">
    <option value="1">Option: Value 1</option>
    <option value="2">Option: Value 2</option>
  </select>

  And changes it to:

  <select id="existingList">
    <option value="1">Option: Value 1</option>
    <option value="3">Option: Value 3</option>
    <option value="2">Option: Value 2</option>
  </select>
*/

規範

規範
HTML
# dom-select-add-dev

瀏覽器相容性