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?
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 todocumentyou getwindow.document. Best practice for creating a global variable in a browser is to add it towindow(globalin Node.js). Here’s an example from jQuery:Some properties on
window(hence some global variables) are read-only, you can’t overwrite them.window.documentis one (tested in Chrome, this is all browser-specific and could change):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
windowproperty (today or in some future browser).At the top level (not inside a function),
vardeclares global variables. Statingvar document = 'foo'at the top level won’t throw an error butdocumentwill still be theDocument, not"foo".As an aside: new-ish browsers (which support ES5) let you create your own read-only globals with
Object.defineProperty:I’ve got three options for you.
Keep using global variables for your elements but leave them alone if they already exist (creating them on
windowexplicitly so the code is clear and cool with ES5):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: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: