HTMLCollection: item() 方法

Baseline 已廣泛支援

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

HTMLCollection 方法 item() 返回集合中指定偏移量處的元素。

注意: 由於 HTMLCollection 的內容是即時更新的,底層 DOM 的更改會(並且確實會)導致集合中各個元素的位置發生變化,因此特定元素的索引值不一定會保持不變。

語法

js
item(index)

引數

index

要返回的 Element 的位置。元素在 HTMLCollection 中的出現順序與它們在文件原始碼中的出現順序相同。

返回值

位於指定索引處的 Element,如果 index 小於零或大於等於 length 屬性,則返回 null

用法說明

item() 方法從 HTMLCollection 返回一個編號的元素。在 JavaScript 中,將 HTMLCollection 視為陣列並使用陣列表示法對其進行索引更為容易。請參見下面的示例

示例

js
const images = document.images; // This is an HTMLCollection
const img0 = images.item(0); // You can use the item() method this way
const img1 = images[1]; // But this notation is easier and more common

規範

規範
DOM
# ref-for-dom-htmlcollection-item①

瀏覽器相容性

另見