Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do I really need to call getElementById()? [duplicate]

Tags:

javascript

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?

like image 796
AlexStack Avatar asked Sep 20 '12 10:09

AlexStack


1 Answers

When creating elements with IDs, the "window" object receives the specific attributes, that's why you can use variables directly, this behavior is deprecated and usually is wrote like this: window.ohlala.innerHTML = "...", this behavior is conserved by the browsers for compatibility with some older code on websites, but it is not recommended to use it in modern websites, always use .getElementById() method, this method is part of a W3C Standard, and you can use it in all modern browsers, in some very old browser versions and < IE7 it will not work. Learn more about DOM (Document Object Model) here: https://developer.mozilla.org/en-US/docs/DOM

like image 190
micnic Avatar answered Oct 25 '22 08:10

micnic