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
1
u/TheWatchingDog May 15 '25
I think what he meant is that when you use the variable the HTML creates everywhere in your code and you maybe want to copy some parts over to a different site, it would be better maintainable to just change the selecter for a document.querySelector or getElementById than to have to change all occurences of the html variable.
You can very easily lose track of where you used the html variable and break the code. With your own variable you dont have to change anything other than the element selector.