在 'document.getElementById('id')[0]' 中 - [0] 是什么意思?



我有一个关于这个代码片段的问题:

var a = document.getElementById("id")[0];对象中的 [0] 是什么意思?

html中的id总是需要是唯一的,document.getElementById返回由这个id表示的元素。document.getElementById不返回NodeList。NodeList 是类似数组的结构,其元素可以通过索引访问,如[0]

由于document.getElementById("id")从不返回NodeList所以document.getElementById("id")[0]是错误的代码

> [0] 表示数组的第一个元素。或字符串的第一个字符。或0对象的属性。

const obj = {0: 'prop'}
const string = 'String';
const array = [1,2,3];
console.log(
obj[0],
string[0],
array[0]
)

document.getElementById("id") 返回 HTMLElement,而不是数组。

我认为这段代码是虚拟复制粘贴的,因为所有其他getElementsBy..函数都返回 HTMLCollection(不是数组,而是可迭代对象)。

或者(可能是)有人用htmlelement设置0属性,如下所示:

id[0] = 'some value';
console.log(
document.getElementById("id")[0]
)
<div id='id'></div>

它很疯狂,但有效..

相关内容

最新更新