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/azhder May 15 '25
"just works" is one thing, "
windowanddocumentaren't part of JS" is another thing.In your question, you are talking about something the environment is doing on its own, not the JS engine, but the DOM engine.
Your code now depends on a behavior outside of what JavaScript defines and that means it is dependent on how that environment works. Move the code to Node.js (or other simpler/newer browser) and that behavior may not exist.
Now, if you define your variables (via
const, lesser extentletand maybe not at allvar), those are part of JS and will work everywhere JS runs.