8

I find it convenient to set a variable with the same name as an element's id, for example:

randomDiv = document.getElementById("randomDiv");
  randomDiv.onclick = function(){ /* Whatever; */ }
  randomDiv.property = "value";

This works in Chrome and Firefox, but not IE8; giving the error Object doesn't support this property or method.

Is creating a variable with a name that matches an element ID wrong (or bad practice) or is this another instance of Internet Explorer acting up?

Gary
  • 13,303
  • 18
  • 49
  • 71

4 Answers4

10

Making global variables automatically is considered bad practice because it can be difficult to tell, looking at some code, whether it is on purpose or you forgot to declare a variable somewhere. Automatic creation of global variables like this doesn’t work in ES5 strict mode and could be phased out phased out in future versions of ECMAScript.

In the browser JavaScript’s global scope is actually window. When you refer to document you get window.document. Best practice for creating a global variable in a browser is to add it to window (global in Node.js). Here’s an example from jQuery:

window.jQuery = window.$ = jQuery;

Some properties on window (hence some global variables) are read-only, you can’t overwrite them. window.document is one (tested in Chrome, this is all browser-specific and could change):

window.document; // → Document
window.document = 'foo'; // → "foo" // It worked!
window.document; // → Document // Hmm, no it didn’t

It turns out that most browsers create properties on window (hence global variables) for each id in the document. Many browsers don’t make them read-only, you can overwrite them with your own, but Internet Explorer does.

This is another reason global variables in JavaScript can be dangerous — one of your ids could match a read-only window property (today or in some future browser).

At the top level (not inside a function), var declares global variables. Stating var document = 'foo' at the top level won’t throw an error but document will still be the Document, not "foo".

As an aside: new-ish browsers (which support ES5) let you create your own read-only globals with Object.defineProperty:

Object.defineProperty(window, 'foo', { value: 'bar', writable: false });
foo = 'baz';
foo; // → "bar"

I’ve got three options for you.

  1. Keep using global variables for your elements but leave them alone if they already exist (creating them on window explicitly so the code is clear and cool with ES5):

    if ( ! window.randomDiv) {
        window.randomDiv = document.getElementById('randomDiv');
    }
    
  2. Create an object, on window, to use as your app’s own namespace which won’t interfere with other libraries or with the browser. This is common and considered pretty good practice, especially if it needs to be accessed across JavaScript files:

    // Early in your code…
    window.Fantabulum = {};
    // Later on…
    Fantabulum.randomDiv = document.getElementById("randomDiv");
    
  3. Avoid making globals. Make sure that your application’s code is inside a function (it should be already so your other variables aren’t global and don’t have the same limitations!), and declare variables for your elements:

    (function(){
        var randomDiv = document.getElementById("randomDiv");
    })();
    
s4y
  • 50,525
  • 12
  • 70
  • 98
  • 1
    One small comment on suggestion #3: the code exactly as you have it will cause syntax errors in most browsers, as it will be [parsed as a function **statement**](http://stackoverflow.com/a/17332932/507784), rather than as a function **expression**, and function statements cannot be followed by `()`. The fix is to surround the `function(){ /* ... */ }` code with parentheses to force it to be parsed as a function expression, i.e. `(function() { /* ... */ }())` or `(function() { /* ... */ })()`. Or assign it to a variable. – GregL Jul 01 '13 at 23:10
3

It is a quirk of IE to create global variables with the same name as element ids and names. You can create a global with the same name, but there are quirks with that.

It's a pretty awful idea. If you don't like typing document.getElementById, just make a small wrapper function for it such as:

funciton get(id) {
  return typeof id == 'string'? document.getElementById(id) : id;
}
RobG
  • 142,382
  • 31
  • 172
  • 209
  • I agree that creating global variables like this is a dangerous feature of JavaScript, but it’s perfectly good practice to store the element in a variable instead of calling `getElementById` each time. – s4y Jul 28 '11 at 00:55
  • That's a pretty nifty function. I don't mind the typing, I just think that it looks cleaner to use a variable name than trying to re-reference the element; specially when I use it over. I can think of a few other examples but I don't think they're worth mentioning. Do you use document.getWhatever each time or do you have a better method? – Gary Jul 28 '11 at 01:01
  • @Sidnicious - quite happy with storing references, just not a fan of making a global variable for every element with an id. – RobG Jul 28 '11 at 01:02
  • @Fantabulum - most script that deals with the UI is initiated by elements, so you already have a reference to the element from the event. Direct access to elements by id is not common in the apps I write, so I don't use getElementById very much and so don't need to wrap it. – RobG Jul 28 '11 at 01:06
0

randomDiv is not an defined / known "global scope variable".

Declaring global variable

Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
  • Alright, maybe calling it a global variable is a misnomer but the questions is why can't variableName === id? Good info though, thanks for the input. – Gary Jul 28 '11 at 00:55
  • 1
    Hi Fantabulum, the variableName you are referring to, is part of JavaScript, while the id is DOM. They are seperate things. – Oh Chin Boon Jul 28 '11 at 01:05
  • Fantabulum, in your above code caption, you are trying to use DOM to get a reference to a HTML form object with the ID randomDiv, however randomDiv is not a global variable. If you are referring to why declaring randomDiv as a global variable doesn't work, that is not one of the ways of declaring global variables in JavaScript. – Oh Chin Boon Jul 28 '11 at 01:17
0

It seems the id becomes automatically a variable! No need to declare it:

<button id="b1">press me</button>
<script>
    b1.onclick = function(){alert("Thanks!")}
</script>

As you see, it works (at least firefox 68) and does not throw any error.

Some more info: