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

浏览器兼容性