Replace getElementById with global variables ?

document.getElementById is one of the widely used methods in the HTML DOM. It will return the specified element or else it will return null.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<body>
<div id="title"></div>
<script>
const element = document.getElementById('title');
console.log(element);
</script>
</body>
<body> <div id="title"></div> <script> const element = document.getElementById('title'); console.log(element); </script> </body>
<body>
   <div id="title"></div>

   <script>
     const element = document.getElementById('title');
     console.log(element);
   </script>
</body>

When we log element to the console, we can see it holds HTMLDivElement.

Do you know but it is not necessary to use document.getElementById. When you add an ID selector with a value to your HTML element, your browser will create a global reference to that element.

Yeah it is true

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<div id="title"></div>
<script>
console.log(title);
</script>
<div id="title"></div> <script> console.log(title); </script>
 <div id="title"></div>

 <script>
      console.log(title);
 </script>

I have not created any variable with name title, but when I log title to the console it will give me a reference to HTMLDivElement. This is same as referring the element using getElementById.

This is not a new feature and it has been around forever or may be for a very long time.

But it is not encouraged to use these global references directly in your javaScript code unless there is a real need to do so. You should always try to use getElementById or querySelector.

Leave a Reply

Your email address will not be published. Required fields are marked *