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

浏览器兼容性

另见