Jump to content
Larry Ullman's Book Forums

Chap. 5 Random.js


Recommended Posts

Hi,

Trying to learn JavaScript. I was playing with the code and I'm a little confused about something seemingly simple. In the code below (from chap 5 random.js), when I comment out the line, var output = document.getElementById('output');, and save the file. When I refresh the browser window it still generates a random number. If I type "output" in the console I get <span id="output">. If I type "output.textContent" I get the random number. It seems as if this variable is not even needed. What is the reason for this?

function showNumbers() {
    'use strict';

    // Variable to store the lucky numbers:
    var numbers = '';

    // Get the numbers:
    for (var i = 0; i < 6; i++) {
        numbers += parseInt((Math.random() * 100), 10) + ' ';
    }

    // Show the numbers:
    var output = document.getElementById('output');
    if (output.textContent !== undefined) {
        output.textContent = numbers;
    } else {
        output.innerText = numbers;
    }

} // End of showNumbers() function.

// Initial setup:
window.onload = showNumbers;


Thanks,
Jeff

Link to comment
Share on other sites

Hello, and welcome to the forums.

 

"output" works without declaring a variable because of a very bad idea originally implemented in IE and later spread to other browsers.

Here's more info about it:

http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables

 

In short, you should always use document.getElementById and a declared variable to grab a hold of and retain a DOM element.

Link to comment
Share on other sites

 Share

×
×
  • Create New...