1

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?

JSFiddle

AKG
  • 2,936
  • 5
  • 27
  • 36
  • This is expected, elements are global on the window object based on ID's etc. – adeneo Mar 04 '14 at 10:44
  • 1
    possible duplicate of [IE/Chrome: are DOM tree elements global variables here?](http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here) – adeneo Mar 04 '14 at 10:44
  • @adeneo you're right. didn't realize that. thanks though! :) – AKG Mar 04 '14 at 10:46

0 Answers0