大网数据广告活动
Web 标准与前端开发

HTMLOptionsCollection: add() method

· 52CE 我爱测

The **`add()`** method of the HTMLOptionsCollection interface adds an HTMLOptionElement or HTMLOptGroupElement to this `HTMLOptionsCollection`.

HTML DOM

The add() method of the HTMLOptionsCollection interface adds an HTMLOptionElement or HTMLOptGroupElement to this HTMLOptionsCollection.

Syntax

add(item)
add(item, before)

Parameters

  • item
    • : An HTMLOptionElement or HTMLOptGroupElement.
  • before
    • : An element of the collection, or a numeric 0-based index representing the element that the item should be inserted before. If omitted, null, or the index does not exist, the new element is appended to the end of the collection.

Return value

None (undefined).

Exceptions

  • HierarchyRequestError DOMException
    • : Thrown if the item passed to the method is an ancestor of the element into which it is to be inserted.

Description

By default, the add() appends the option or optgroup passed as the parameter to the end of the collection. You can define where the added <option> or <optgroup> should be placed by specifying the before parameter. The before is the <option> element or a numeric 0-based index of the <option> element the added element should precede.

If the before parameter is null or out of range (or omitted), the <option> or <optgroup> will be appended as the last element in the collection, outside of any optgroup. If the <option> referenced by the before parameter is in an optgroup, an added HTMLOptionElement will be in the same group.

The <optgroup> element can only contain <option> elements as child nodes. The add() method will successfully add an HTMLOptGroupElement to the end of the HTMLOptionsCollection or between <optgroup> elements only. In other words, attempting to add an HTMLOptGroupElement before an <option> within an <optgroup> may silently fail if the <option> referenced by the before parameter is not the first <option> within its <optgroup>.

Examples

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

Specifications

Browser compatibility

See also

  • select
  • HTMLOptionsCollection.remove
  • HTMLOptionsCollection.length
  • HTMLOptionsCollection.selectedIndex

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。