mike m
mike m

Reputation: 135

JavaScript document.getElementById(“id”) and element id attribute

I have:

<div id="myDiv1"></div>
<div id="myDiv2"></div>

In JavaScript, I can set div innerHTML by writing:

myDiv1.innerHTML = "myDiv1, Hi!"

or

document.getElementById("myDiv2").innerHTML = "myDiv2, Hi!"

Why should I use document.getElementById when I can simply use element Id ? Is this working every time or only in some special scenarios (like simple sample)?

thanks,

Mike

Upvotes: 7

Views: 4122

Answers (2)

Thakur
Thakur

Reputation: 557

when you write

myDiv1.innerHTML = "myDiv1, Hi!"

you are calling window object, so actual call is like this

window.myDiv1.innerHTML = "myDiv1, Hi!"

This behavior is deprecated now and to be avoided. Instead we should use

document.getElementById` 

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075755

Why should I use document.getElementById when I can simply use element Id ?

To avoid conflicts. The global namespace on browsers is incredibly crowded, all sorts of things are dumped in there, including (as you've found) globals referring to any element with an id (so-called "automatic globals").

In contrast, getElementById only does what it says, finds an element by its id; it's more constrained. (Other than bugs in old versions of IE, which also looked at elements with name attributes.)

Upvotes: 8

Related Questions