0

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

Nikki
  • 3,664
  • 2
  • 15
  • 14
  • possible duplicate of [IE/Chrome: are DOM tree elements global variables here?](http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here) – Joseph May 04 '12 at 11:10

2 Answers2

4

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 myelement and 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 assign myelement to the corresponding node is run first either way.

st-boost
  • 1,877
  • 1
  • 14
  • 17
0

No it does not hurt performance, Firefox also allow that. even if there is a variable name conflict condition arise then local variable will get the priority.

like

<img src="picture.jpg" id="myelement" />

function stuff()

{

var myelement="test variable";

myelement.style.display="none";     //this will result in error because myelement is a variable now

}

IuR
  • 154
  • 3