I noticed while playing around with Chrome that both of these functions work the same:
<img src="picture.jpg" id="myelement" />
function stuff(){
var x=document.getElementById("myelement");
x.style.display="none";
}//works almost everywhere
function stuff(){
myelement.style.display="none";
}//only works in Chrome
Why does Chrome allow me access the element straight from the id without using ‘getElementById’?
And is it bad practice to do it this way?
Does it hurt performance?
Thanks
Chrome automatically creates global variables corresponding to each element with an id. It is a very bad idea to use these variables in production code because no variables are static in javascript – somebody could have later assigned something else to
myelementand you would have no way of knowing.If you do use this feature (presumably in a testing environment, like the console), I would guess it is faster than
getElementById(), as the code to assignmyelementto the corresponding node is run first either way.