7

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
mike m
  • 135
  • 9
  • In your first snippet, you are using `myDiv1`. How have you retrieved it? – Giorgio Feb 05 '15 at 10:03
  • 1
    No, you can't. Just you can assign to var every one div by ID, but nothing without this assignment. – pavel Feb 05 '15 at 10:03
  • 1
    This does work, but [it's a bad idea](http://stackoverflow.com/q/25325221/417562). – lonesomeday Feb 05 '15 at 10:04
  • It is true that browsers expose elements with ids as global variables. But this is not reliable and error prone, as any globals in general. Plus there is no guarantee that older browsers will do the same. – dfsq Feb 05 '15 at 10:04
  • @Giorgio: It's an automatic global, because the element has an `id`. – T.J. Crowder Feb 05 '15 at 10:04

2 Answers2

8

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

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` 
Thakur
  • 559
  • 6
  • 15
  • *"This behavior is deprecated now..."* Not as far as I'm aware. The W3C effort to document the Window object didn't mention this, true, but it's also been dead for eight years and never got past a very rough draft stage. The WHAT-WG's version of the "HTML" spec (which is about a **lot** more than HTML) [documents this aspect of Window](https://html.spec.whatwg.org/#named-access-on-the-window-object) without calling it "deprecated." I agree it's best to avoid using it. – T.J. Crowder Feb 05 '15 at 10:35