Is it allowed to use an ID as a variable identifier?

One method I often use is assigning a variable with the same name as the id of an element, like this:

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

This technique functions correctly in Chrome and Firefox, however it encounters issues in IE8, displaying the error message Object doesn't support this property or method.

Is it considered incorrect or poor practice to create a variable using the same name as an element ID, or is this simply another instance of Internet Explorer's quirks?

Answer №1

It is commonly frowned upon to automatically create global variables because it can lead to confusion in the codebase, making it difficult to determine if a variable was intentionally set as global or if it was an oversight. The automatic creation of global variables does not function in ES5 strict mode and may be phased out in future ECMAScript releases.

In JavaScript within a browser, the global scope is represented by window. When referencing document, you are essentially referring to window.document. The recommended practice for defining global variables in a browser environment is to add them directly to window (or global in Node.js). Here's an example from jQuery:

window.jQuery = window.$ = jQuery;

Some properties on window (and thus global variables) are read-only and cannot be overwritten. For instance, window.document is read-only (as tested in Chrome):

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

Interestingly, most browsers create properties on window (creating global variables) for each id in the document. Although many browsers allow these values to be changed, Internet Explorer enforces read-only status.

This showcases another reason why global variables in JavaScript can pose risks—there is a potential for your ids to conflict with read-only window properties either presently or in future browser versions.

At the top level (outside of a function), var defines global variables. Declaring var document = 'foo' at the top level will not throw an error, but document would still reference Document, not "foo".

As a side note, modern browsers supporting ES5 enable the creation of read-only globals using Object.defineProperty:

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

I offer three suggestions for you to consider:

  1. Continue utilizing global variables for your elements while ensuring they are only created on window if they do not already exist, thereby maintaining clarity and compatibility with ES5:

    if ( ! window.randomDiv) {
        window.randomDiv = document.getElementById('randomDiv');
    }
    
  2. Establish an object on window to serve as your application's namespace, preventing conflicts with other libraries or browser components. This approach is widely accepted and beneficial, particularly when needing cross-file accessibility:

    // At the beginning of your code…
    window.Fantabulum = {};
    // Later on…
    Fantabulum.randomDiv = document.getElementById("randomDiv");
    
  3. Avoid reliance on global variables. Ensure that your application's logic is encapsulated within a function (which should already be the case to prevent leakage of variables) and declare element-specific variables within it:

    (function(){
        var randomDiv = document.getElementById("randomDiv");
    })();
    

Answer №2

One interesting fact about Internet Explorer is its tendency to create global variables with the same names as element IDs and names. While technically possible to do so, there are some quirks associated with it.

However, this practice is not recommended and is generally considered a bad idea. If you find yourself tired of repeatedly typing document.getElementById, you can simply create a short wrapper function like this:

function get(id) {
  return typeof id === 'string' ? document.getElementById(id) : id;
}

Answer №3

randomDiv is not a recognized "global scope variable".

Learn about declaring global variables

Answer №4

It's interesting how the id automatically becomes a variable without needing to declare it:

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

Surprisingly, this code snippet works flawlessly in Firefox 68 and doesn't generate any errors.

If you'd like more information on this topic, check out these resources:

  • Why don't we just use element IDs as identifiers in JavaScript?
  • JavaScript document.getElementById(“id”) and element id attribute

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with automatic form submission

What is the best way to automatically submit my form once the timer runs out and also when the refresh button is clicked? I have encountered an issue where every time I try to refresh the page, it prompts for user confirmation. If I click cancel, it stay ...

Error: monaco has not been declared

My goal is to integrate the Microsoft Monaco editor with Angular 2. The approach I am taking involves checking for the presence of monaco before initializing it and creating an editor using monaco.editor.create(). However, despite loading the editor.main.j ...

Ways to adjust the height of one panel based on the height of surrounding panels

I have a layout with three panels: two on the left side and one on the right. <div class="row"> <div class="col s6"> <div class="panel"> content1 </div> <div class="panel"> ...

Presentation - hyperlink only functioning for final slide

I have a question about Lean Slider, which you can check out at My goal is to link each slide to a different URL. However, I'm facing an issue where only the code in the last slide seems to be executed and applied to all other slides. For example, if ...

Error message: "Unable to access 'title' property of an undefined value" for an item with a length of 1

Despite the fact that the collection is not undefined and the `title` attribute is also not undefined, for some reason I am unable to read the `title` attribute from the `received` variable. The error indicates that it is undefined. var received = document ...

Variations in how words are organized within a sentence

Can you help me devise an algorithm to identify all possible combinations of word groupings in a sentence without changing the order of the words? For example, for the sentence "the test case phrase," the various combinations would include: ['the te ...

Using Next.js for dynamic routing with JSON arrays in getStaticPaths

I am currently facing an issue while trying to incorporate a json file with multiple arrays into my Next.js application. The structure of the json file is quite complex, and I'm unsure about how to convert it into a format that can be effectively util ...

What is the best way to identify and list distinct values within a MongoDB collection when the values are arrays of objects?

Is there a way to extract unique values from a collection that consists of an array of objects? While the distinct method works for strings and numbers, I'm facing a situation where the values are objects. Here's a simplified version of the mode ...

I want the name of the hospital to be displayed in the dropdown menu with a shortened version of the hospital's name appearing

Check out my code snippet: here import Autocomplete from "@mui/material/Autocomplete"; import TextField from "@mui/material/TextField"; import React, { useState } from "react"; const hospitalList = { docs: [ { _id: ...

The problem of "undefined function appendTo" is causing issues

My jQuery code looks like this: $(function() { var productTextTemplate = $('#product-text-template').html(); var productTemplate = $('product-template').html(); var product = productTextTemplate.appendTo(productTemplate); a ...

Access the contents of the selected cell in the MUI datagrid

When I choose a row from the datagrid, my attempt to access each cell value in that row always returns "undefined" when using selectedRowData.email. How can I correctly retrieve the data from a selected row's cells? <DataGrid checkboxSe ...

How to retrieve the same value from multiple selections using Vanilla JavaScript and multiple select options?

Why do we consistently receive the same value and index when using the ctl key to select multiple options? document.querySelector('select').addEventListener('change', function(e) { console.log(this.selectedIndex) console.log(e.ta ...

What is the best way to create separate arrays for every element in my object, containing a total of four arrays to efficiently produce a weekly forecast?

Hey there, I'm back with an update on my ongoing project. I've encountered a major challenge while trying to incorporate a 7-day forecast display in my app. Something along these lines: https://i.stack.imgur.com/xJA4M.png https://i.stack.imgur. ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

What is the best way to determine the file size using Node.js?

My current challenge involves using multer for uploading images and documents with a restriction on file size, specifically limiting uploads to files under 2MB. I have attempted to find the size of the file or document using the code below, but it is not p ...

Utilizing the map() function to iterate through a list of outcomes and assigning the resulting array as the state of a component in ReactJS

Currently, I am facing an issue with assigning an array value to the state in my react project. In order to do this, I have initialized my state as follows: constructor(props) { super(props); this.state = { category: [] } } My objec ...

Javascript code generated by PHP is failing to run

When you select an option from the dropdown below: <select id='dropdown' name='dropdown' onchange='showChart(this.value)'> <option value="1">Foo</value> <option value="2">Bar</value> </select& ...

Switching from using jQuery to Mootools in a short script that helps to balance the heights of

I have a simple script that I frequently use in jQuery to make boxes equal heights. Now, I need to convert it to mootools for a new project where the boxes will be floated left at thirds using style sheets. <div id="box1" class="equals">content he ...

What is causing the issue with Vue.js :class not functioning properly when it relies on a property of a list

Here is a snippet of my HTML code: <tr v-for="product in products" :class="{'bg-red': product.toWrite }" :key="product.name"> <td @click="setObjectToWrite(product.name)" class="show-hover&qu ...

Determine if the input number exceeds a specified threshold by implementing JavaScript

My attempt at performing calculations on a page is not yielding the desired results. I have tinkered with the code below, but it doesn't seem to be working as expected. Can anyone provide guidance on where I might be going wrong? Specifically, I want ...