Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
I just stumbled upon an unexpected but useful behavior in the browser: It creates a variable for every element that has an ID in my html code. So when I have:
<div id="ohlala"> ... </div>
the browser seem to run this code behind the scene:
var ohlala = document.getElementById("ohlala");
so I can easily change the text of that element by:
ohlala.innerHTML="test"
Try it online: http://jsfiddle.net/Facby/
The question is: why would I need to write the document.getElementById()
bit myself? How portable is that code? I tried in Opera, FireFox and Chrome and it works! Can I rely on this functionality? Does the browser always create variables for every element with id? In that case I have to be more careful about the names that are used in my javascript code not to conflict with similar ids from the HTML, right?