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

瀏覽器相容性