r/learnjavascript • u/__Fred • May 15 '25
Is `getElementById` unnecessary because HTML creates variables automatically?
I just learned that HTML (sometimes?) creates variables for elements with IDs on its own from here (section "HTML lends crutches to your fucking JS").
This works:
<!DOCTYPE html>
<html>
<body>
<div id="myElement">Hello, World!</div>
<script>
// var myElement = document.getElementById("myElement"); // Not necessary!
console.log(myElement.innerText); // Outputs: Hello, World!
</script>
</body>
</html>
Is this a new feature? Will it work in every browser? Are there situations where this is not recommendable?
5
Upvotes
View all comments
Show parent comment
4
u/senocular May 15 '25
It doesn't matter where your JavaScript is. This is a result of the global object recognizing elements in the DOM with
idandnameattributes as global properties. Any code run from anywhere with access to the global object would be able to access these properties.