+ 1
Why do the console write "null" ?
5 Answers
+ 3
That's because his/her code is running once all the elements of the page have been loaded. In your case the script was running before the elements were loaded
https://www.w3schools.com/jsref/event_onload.asp
+ 1
It is because in the first line you are obtaining an element that does not exist (there is no element with the id 'Block') and then you are showing that element in the console (since there is no element with the id 'Block', your variable is equal to null )
+ 1
window.onload = function() {
var block = document.getElementById("block");
console.log(block); // <-- try alert(block); instead here.
};
Note that in this case console.log() won't show anything. Try using alert() instead. alert() will show the string definition of the HTML object in this case.
0
But the id of my img is block what should i do ?
0
Why do my code doesn't works but your code works ?