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①

浏览器兼容性

另见