HTMLOptionsCollection:add() 方法
HTMLOptionsCollection 介面的 add() 方法將一個 HTMLOptionElement 或 HTMLOptGroupElement 新增到此 HTMLOptionsCollection。
語法
js
add(item)
add(item, before)
引數
返回值
無(undefined)。
異常
HierarchyRequestErrorDOMException-
如果傳遞給方法的
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 |
瀏覽器相容性
載入中…