document.getElementsByTagName('div')
returns an array of elements.
document.getElementsByTagName('div')[0]
returns a single element.
but for some reason,
var firstDiv = document.getElementsByTagName('div')[0]
returns ‘undefined’. Strangely, global variables do not seem to have this problem.
firstDiv = document.getElementsByTagName('div')[0]
returns an element.
The
varkeyword is to blame. Note that thisis a variable declaration while this
is an expression statement. Expression statement returns a value. Declarations do not. Declaration which contains initialization with some expression initializes the variable, but the value of the initializer does not become the value of the declaration (since declarations do not have a value).
All of these “return” undefined:
All of these return something (an array of divs or the first div):