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

HTMLCollection.namedItem()

· 52CE 我爱测

HTMLCollection 接口的 **`namedItem()`** 方法返回第一个与集合中的 `id` 或者 `name` 属性匹配成功的 Element,如果没有匹配成功,则返回 `null`。

DOM

HTMLCollection 接口的 namedItem() 方法返回第一个与集合中的 id 或者 name 属性匹配成功的 Element,如果没有匹配成功,则返回 null。

在 JavaScript 中,对一个 String 使用数组括号语法,例如 collection["value"] 等价于 collection.namedItem("value")。

语法

const item = collection.namedItem(key);

参数

  • key 是一个字符串,表示我们正在查找元素的 id 或者 name 属性。

返回值

  • item 是 HTMLCollection 第一个与 key 匹配的 Element,如果没有,则返回 null。

示例

HTML

<div id="personal">
  <span name="title">Dr.</span>
  <span name="firstname">John</span>
  <span name="lastname">Doe</span>
  <span id="degree">(MD)</span>
</div>

JavaScript

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["firstname"];
const lastnameSpan = container.children.lastname;

// 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);

示例

规范

浏览器兼容性

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

资料来源与适用范围

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

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

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