HTMLCollection: namedItem() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

HTMLCollection 接口的 namedItem() 方法返回集合中第一个 idname 属性与指定名称匹配的 Element,如果没有元素匹配,则返回 null

在 JavaScript 中,除了调用 collection.namedItem("value"),你还可以直接通过 collection["value"] 访问该名称,除非该名称与现有 HTMLCollection 属性发生冲突。

语法

js
namedItem(key)

参数

key

一个字符串,表示我们正在寻找的元素的 idname 属性的值。

返回值

集合中第一个与 key 匹配的 Element,如果没有找到,则返回 null。如果 key 是空字符串,则始终返回 null

示例

HTML

html
<div id="personal">
  <span name="title">Dr.</span>
  <span name="first-name">Carina</span>
  <span name="last-name">Anand</span>
  <span id="degree">(MD)</span>
</div>

JavaScript

js
const container = document.getElementById("personal");

// Returns the HTMLSpanElement with the name "title" if no such element exists null is returned
const titleSpan = container.children.namedItem("title");

// The following variants return undefined instead of null if there's no element with a matching name or id
const firstNameSpan = container.children["first-name"];
const lastNameSpan = container.children["last-name"];

// Returns the span element with the id "degree"
const degreeSpan = container.children.namedItem("degree");

const output = document.createElement("div");
output.textContent = `Result: ${titleSpan.textContent} ${firstNameSpan.textContent} ${lastNameSpan.textContent} ${degreeSpan.textContent}`;

container.insertAdjacentElement("afterend", output);

规范

规范
DOM
# dom-htmlcollection-nameditem-key

浏览器兼容性