我想从 HTMLCollection 中获取一个元素。document.getElementsByClassName 的返回正是我所期望的,但是当我尝试访问它的任何属性时,看起来那里什么都没有。这是我的代码(此代码在一个 .js 文件中运行,我将其放入我的 index.html 中):
document.addEventListener('DOMContentLoaded', function () {
var code = document.getElementsByClassName('CodeMirror-code');
console.log(code);
console.log(code[0]); //undefined
console.log(code.length); //0
}
这是控制台日志:
HTMLCollection(1)
0: div.CodeMirror-code //this is the div I want to access
length: 1
__proto__: HTMLCollection
undefined
0
另外,如果我在控制台中输入:
var code = document.getElementsByClassName('CodeMirror-code');
code[0]
我得到回报:
<div class="CodeMirror-code">...</div>
这正是我正在寻找的,但这不是我在脚本中得到的结果。