I came across the following gotcha I can't seem to wrap my head around.
Say I want to set the innerHTML
of a div
with the #show5
id via Javascript.
var show5 = document.getElementById('show5');
show5.innerHTML = 'matthew mcconaughhey';
The code above makes sense: first you assign the div
to show5
, and then you set the innerHTML
of show5
. Nothing special here.
However, I noticed that even if I leave out the first line, the code still works. Console doesn't even show any errors:
// var show5 = document.getElementById('show5'); - commented out
show5.innerHTML = 'matthew mcconaughhey';
You'd expect the code to fail here. But it is working. Can anyone explain to me why this is or is there something wrong with the logic on my part?