diff --git a/files/en-us/web/api/htmloptionscollection/add/index.md b/files/en-us/web/api/htmloptionscollection/add/index.md new file mode 100644 index 000000000000000..f0e3d23d613c721 --- /dev/null +++ b/files/en-us/web/api/htmloptionscollection/add/index.md @@ -0,0 +1,67 @@ +--- +title: "HTMLOptionsCollection: add() method" +short-title: add() +slug: Web/API/HTMLOptionsCollection/add +page-type: web-api-instance-method +browser-compat: api.HTMLOptionsCollection.add +--- + +{{APIRef("HTML DOM")}} + +The **`add()`** method of the {{DOMxRef("HTMLOptionsCollection")}} interface adds an {{domxref("HTMLOptionElement")}} or {{domxref("HTMLOptGroupElement")}} to this `HTMLOptionsCollection`. + +## Syntax + +```js-nolint +add(item) +add(item, before) +``` + +### Parameters + +- `item` + - : An {{domxref("HTMLOptionElement")}} or {{domxref("HTMLOptGroupElement")}}. +- `before` {{optional_inline}} + - : 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 ({{jsxref("undefined")}}). + +### Exceptions + +- `HierarchyRequestError` {{DOMxRef("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 {{HTMLelement("option")}} or {{HTMLelement("optgroup")}} passed as the parameter to the end of the collection. You can define where the added `` should be placed by specifying the `before` parameter. The `before` is the `` will be appended as the last element in the collection, outside of any {{HTMLelement("optgroup")}}. If the `` element can only contain `` elements only. In other words, attempting to add an `HTMLOptGroupElement` before an `` may silently fail if the ``. + +## Examples + +```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 +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- {{HTMLElement("select")}} +- {{DOMxRef("HTMLOptionsCollection.remove")}} +- {{DOMxRef("HTMLOptionsCollection.length")}} +- {{DOMxRef("HTMLOptionsCollection.selectedIndex")}} diff --git a/files/en-us/web/api/htmloptionscollection/index.md b/files/en-us/web/api/htmloptionscollection/index.md index b2900da464ba54c..7f8b356a2f01635 100644 --- a/files/en-us/web/api/htmloptionscollection/index.md +++ b/files/en-us/web/api/htmloptionscollection/index.md @@ -13,13 +13,20 @@ The **`HTMLOptionsCollection`** interface represents a collection of [`