Is there any reason to use document.getElementById instead of the ID itself?

28 Views Asked by At

For example, to remove an element from the DOM, myEl.remove() works just as well (in Firefox and Chrome) as document.getElementById("myEl").remove()

1

There are 1 best solutions below

0
Ry- On

A couple, including name collisions with existing properties of window (which might change over time as new APIs are added):

console.log(name === document.getElementById('name'));
<div id="name"></div>

and static analysis (is your undeclared variable a mistake, or do you expect it to be part of the document?) both by automated linters and human readers.