【发布时间】:2018-06-08 22:16:48
【问题描述】:
我想从 HTMLCollection 中获取一个元素。 document.getElementsByClassName 的返回正是我所期望的,但是当我尝试访问它的任何属性时,看起来那里什么都没有。这是我的代码(此代码在我的 index.html 中的 .js 文件中运行):
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>
这正是我要寻找的,但这不是我在脚本中得到的结果。
【问题讨论】:
-
或者在DOM完全加载之前执行脚本(脚本在文档头部,不附加DOMContentLoaded事件)
-
我在问题中添加了更多上下文,不幸的是,我正在现有项目之上构建,我不知道何时/如何添加 div,但我知道 DOM 已加载因为那是函数被调用的时候
-
let code = [...code] 将您的集合包装在一个数组中
标签: javascript html htmlcollection