HTMLFormControlsCollection: namedItem() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

HTMLFormControlsCollection.namedItem() 方法返回集合中nameid與指定名稱匹配的 RadioNodeListElement,如果沒有節點匹配,則返回null

請注意,此版本的 namedItem() 隱藏了從 HTMLCollection 繼承的版本。與該版本一樣,在 JavaScript 中,使用帶有 String 的陣列括號語法(例如 collection["value"])等同於 collection.namedItem("value")

語法

js
namedItem(name)
[name]

引數

name

一個字串,將用於與此 HTMLFormControlsCollection 物件中控制元件的 nameid 屬性進行匹配。

返回值

示例

使用 namedItem()

HTML

html
<form>
  <label for="notes">Notes:</label>
  <input id="notes" name="my-form-control" type="text" />

  <label for="start">Start date:</label>
  <input id="start" name="my-form-control" type="date" />
</form>

<div id="output"></div>

JavaScript

js
const form = document.querySelector("form");
const items = form.elements.namedItem("my-form-control");

const output = document.querySelector("#output");
const itemIDs = Array.from(items)
  .map((item) => `"${item.id}"`)
  .join(", ");
output.textContent = `My items: ${itemIDs}`;

結果

規範

規範
HTML
# dom-htmlformcontrolscollection-nameditem-dev

瀏覽器相容性

另見