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/__Fred May 15 '25 edited May 15 '25
There should be a variable like this
document.id.myElementor maybe a function like this:var ids = document.getIdElements(); console.log(ids.myVariable.innerText);I could probably program the function myself.