HTMLOptionsCollection:add() 方法

HTMLOptionsCollection 介面的 add() 方法將一個 HTMLOptionElementHTMLOptGroupElement 新增到此 HTMLOptionsCollection

語法

js
add(item)
add(item, before)

引數

item

一個 HTMLOptionElementHTMLOptGroupElement

before 可選

集合中的一個元素,或者一個數字(0-based 索引),表示 item 應該插入到哪個元素之前。如果省略、為 null 或索引不存在,則新元素將被追加到集合的末尾。

返回值

無(undefined)。

異常

HierarchyRequestError DOMException

如果傳遞給方法的 item 是要插入元素的一個祖先,則會丟擲此錯誤。

描述

預設情況下,add() 方法會將作為引數傳遞的 <option><optgroup> 追加到集合的末尾。您可以透過指定 before 引數來定義新增的 <option><optgroup> 的位置。before<option> 元素,或者是一個數字(0-based 索引),表示要新增的元素應該在此 <option> 元素之前。

如果 before 引數為 null 或超出範圍(或被省略),則 <option><optgroup> 將作為集合中的最後一個元素追加,位於任何 <optgroup> 之外。如果 before 引數引用的 <option> 位於一個 <optgroup> 中,則新增的 HTMLOptionElement 將位於同一個組中。

<optgroup> 元素只能包含 <option> 元素作為子節點。add() 方法只會成功將 HTMLOptGroupElement 新增到 HTMLOptionsCollection 的末尾,或者新增到 <optgroup> 元素之間。換句話說,嘗試在 <optgroup> 內的 <option> 之前新增 HTMLOptGroupElement,如果 before 引數引用的 <option> 不是其 <optgroup> 內的第一個 <option>,則可能會靜默失敗。

示例

js
const optionList = document.querySelector("select").options;
const firstOption = document.createElement("option");
firstOption.text = "new item";
optionList.add(firstOption, 0); // added as the first item
optionList.add(optionList[0]); // moves the first item to the end

規範

規範
HTML
# dom-htmloptionscollection-add-dev

瀏覽器相容性

另見