11
In Javascript, you can refer to any element that has a id
(and in some cases a name
) using simply an identifier with the same name - without the need to declare it:
<div id="teste">Teste</div>
console.log(teste); // <div id="teste">Teste</div>
Except, of course, if there is already a variable with the same name:
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 function built-in, 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 feature? We should only use document.getElementById
instead? Or it would be a simple matter of using only "healthy" names for our element ids (i.e. not using anything that is already defined in the Javascript language)?
Li some opinions in Soen - in general saying to nay use - as well as a discussion in W3.org with arguments against and for, but I am not sure. There is some objective reason to avoid this functionality?
P.S. Although there was already pressure for this functionality to be restricted to "quirks mode", apparently it was standardized by HTML5 - so that although had past incompatibilities the future browsers should give consistent support to it.
It’s not an answer per se, but I think you’ve already answered the question. Using ids directly is a house of cards, at any time someone can declare a variable and break all functionality.
– Anthony Accioly
@Anthonyaccioly I agree! I thought now: it is also possible that in the future browsers will add a new property - with the same name of a
id
your - and with it break your code.– mgibsonbr
That is precisely why
document.getElementById
. Always use it.– user11833
Look more and more the worse thing instead of better, I’m reading here and it’s fun as we Web developers suffer!
– user6026
@Harrypotter Once I read I don’t know where (in case, talking about safety) that "the web is like a car with 1000 pedals of acceleration and no brakes; the only way to stop the car is to ensure that none of the 1000 pedals is pressed..." Every time new features appear (which, I admit, are often quite cool) and with them a lot of problems. And yet the tendency [of the entities responsible for standardization] is to "ignite it" more and more. It is by these and others that I navigate with Javascript disabled (whitelisted) by default...
– mgibsonbr
@mgibsonbr worse than that, it’s not easy no ...
– user6026