Jump to content
Larry Ullman's Book Forums

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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...