0
I wonder why my code has an error.Please help me!
3 Answers
+ 5
Embed your code in a function assigned to the 'onload' event of 'window' object (or in the 'onload' attribute of <body> element -- that's the same event), to the 'DOMContentLoaded' event of 'document' object, or even in a <script> element after the element you want to access with Javascript, to be sure that this element exists when your script run ;)
Anyway, the 'DOMContentLoaded' event can only be registered for listening through the .addEventListener() method (or .attachEvent() method for oldest browsers versions): http://www.javascripter.net/faq/addeventlistenerattachevent.htm
document.addEventListener('load', function() {
var a = document.getElementById("box").innerText;
console.log(a);
});
+ 2
You need to make sure the DOM is ready. Wrap your code in an onload function:
window.onload = function() {
var a = document.getElementById("box").innerText;
console.log(a);
};