Reputation: 125
I would like to get an element from an HTMLCollection. The return of document.getElementsByClassName is exactly what I was expecting but when I try to access any attributes of it, it looks like there is nothing there. Here is my code (this code is run in a .js file that I src into my 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
}
and here are the console logs :
HTMLCollection(1)
0: div.CodeMirror-code //this is the div I want to access
length: 1
__proto__: HTMLCollection
undefined
0
also, If I enter in the console:
var code = document.getElementsByClassName('CodeMirror-code');
code[0]
I get the return:
<div class="CodeMirror-code">...</div>
which is exactly what I am looking for, but that is not the result I get in the script.
Upvotes: 5
Views: 3182
Reputation: 42736
CodeMirror adds it's various DOM elements to the DOM after the CodeMirror()
constructor is called or after CodeMirror.fromTextArea()
is called.
So you can't simply wait for the various DOM ready events in order to find the element you are looking for. You can either pass the constructor a function which you can then manually add the editor to the DOM and then do a search. Or setup a custom CodeMirror event listener.
CodeMirror initialization hook
CodeMirror.defineInitHook(function(cmInstance){
var codeDiv = document.querySelector('.CodeMirror-code');
console.log(codeDiv);
});
var myCodeMirror = CodeMirror(document.body);
CodeMirror manual adding
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);
});
Demo
CodeMirror.defineInitHook(function(cmInstance){
DoWork( document.querySelector('.CodeMirror-code') );
});
var myCodeMirror = CodeMirror(document.body);
function DoWork(codeDiv){
console.log(codeDiv);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.38.0/codemirror.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.38.0/codemirror.min.js"></script>
Upvotes: 1
Reputation: 3278
You might be doing this code before the elements have been rendered on the screen. That's why when you do it in the console it works.
Here are two options:
Try changing the js code to happen onload
of body. If you don't know what onload
is check out this: https://www.w3schools.com/Jsref/event_onload.asp
Try changing the js code to happen when the DOMContentLoaded
listener comes up. Learn about how that works here: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Upvotes: 1