JavaScript document.getElementById ("id") and id attribute
I have:
<div id="myDiv1"></div> <div id="myDiv2"></div> In JavaScript, I can set the innerHTML div by writing:
myDiv1.innerHTML = "myDiv1, Hi!" or
document.getElementById("myDiv2").innerHTML = "myDiv2, Hi!" Why should I use document.getElementById when I can just use the element id? Does it work every time or only in some special scenarios (for example, a simple pattern)?
thanks,
Mike
Why should I use document.getElementById when I can just use the element id?
To avoid conflicts. The global namespace in browsers is incredibly crowded, there are all sorts of things, including (as you already found) global values ββthat refer to any element with id (the so-called "automatic global variables").
On the contrary, getElementById does just what it says, finds the element with its id ; he is more limited. (Except for bugs in older versions of IE that also looked at elements with name attributes.)