In Javascript, you can reference any element that has a id
(and in some cases a name
) by simply using an identifier with the same name - without having to declare it: / p>
<div id="teste">Teste</div>
console.log(teste); // <div id="teste">Teste</div>
Except, of course, if a variable with the same name already exists:
console.log(teste); // undefined
var teste = 10;
console.log(teste); // 10
Or if the id
in question is already a property of Window
(as a built-in function, for example):
<div id="alert">Teste</div>
console.log(alert); // function alert() { [native code] }
Given these inconsistencies, I ask: is it bad to use this functionality? Should we only use document.getElementById
instead? Or would it be a simple matter of only using "healthy" names for the ids of our elements (ie not using anything that is already defined in the JavaScript language)?
Li some reviews in SOen - usually saying no to use - as well as a discussion on w3.org with arguments against and for, but I'm not sure. Is there any objective reason to avoid this functionality?
P.S. Although there was pressure for this functionality to be restricted to quirks mode, it was apparently standardized by HTML5 - so that even though there were incompatibilities in the past, future browsers must consistently support it.