无法从 getElementsByClassName 访问 HTMLCollection 中的元素

Eth*_*cre 5 html javascript htmlcollection

我想从 HTMLCollection 中获取一个元素。document.getElementsByClassName 的返回正是我所期望的,但是当我尝试访问它的任何属性时,看起来那里什么也没有。这是我的代码(此代码在 .js 文件中运行,我将其 src 到我的 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
}
Run Code Online (Sandbox Code Playgroud)

这是控制台日志:

HTMLCollection(1)
   0: div.CodeMirror-code        //this is the div I want to access
   length: 1
   __proto__: HTMLCollection
undefined
0
Run Code Online (Sandbox Code Playgroud)

另外,如果我在控制台中输入:

var code = document.getElementsByClassName('CodeMirror-code');
code[0]
Run Code Online (Sandbox Code Playgroud)

我得到回报:

<div class="CodeMirror-code">...</div>
Run Code Online (Sandbox Code Playgroud)

这正是我正在寻找的,但这不是我在脚本中得到的结果。

Pat*_*ans 1

CodeMirror()CodeMirror 在调用构造函数之后或CodeMirror.fromTextArea()调用之后将其各种 DOM 元素添加到 DOM 。

因此,您不能简单地等待各种 DOM 就绪事件来找到您要查找的元素。您可以向构造函数传递一个函数,然后您可以手动将编辑器添加到 DOM 中,然后进行搜索。或者设置自定义 CodeMirror 事件侦听器。

CodeMirror 初始化挂钩

CodeMirror.defineInitHook(function(cmInstance){
  var codeDiv = document.querySelector('.CodeMirror-code');
  console.log(codeDiv);
});
var myCodeMirror = CodeMirror(document.body);
Run Code Online (Sandbox Code Playgroud)

CodeMirror手动添加

var myCodeMirror = CodeMirror(function(editor){
  //add the editor to the DOM
  document.body.appendChild(editor);

  var codeDiv = document.querySelector('.CodeMirror-code');
  //either of these will work
  var codeDiv = editor.querySelector('.CodeMirror-code');

  console.log(codeDiv);
});
Run Code Online (Sandbox Code Playgroud)

演示

CodeMirror.defineInitHook(function(cmInstance){
  var codeDiv = document.querySelector('.CodeMirror-code');
  console.log(codeDiv);
});
var myCodeMirror = CodeMirror(document.body);
Run Code Online (Sandbox Code Playgroud)
var myCodeMirror = CodeMirror(function(editor){
  //add the editor to the DOM
  document.body.appendChild(editor);

  var codeDiv = document.querySelector('.CodeMirror-code');
  //either of these will work
  var codeDiv = editor.querySelector('.CodeMirror-code');

  console.log(codeDiv);
});
Run Code Online (Sandbox Code Playgroud)