HTMLOptionsCollection:add() 方法
HTMLOptionsCollection
接口的 add()
方法将一个 HTMLOptionElement
或 HTMLOptGroupElement
添加到此 HTMLOptionsCollection
。
语法
js
add(item)
add(item, before)
参数
返回值
无(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 |
浏览器兼容性
加载中…