TFotH 0 Posted November 26, 2014 Report Share Posted November 26, 2014 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 Quote Link to post Share on other sites
HartleySan 826 Posted November 26, 2014 Report Share Posted November 26, 2014 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. Quote Link to post Share on other sites
Recommended Posts
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.