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

5
  • In your first snippet, you are using myDiv1. How have you retrieved it? Commented Feb 5, 2015 at 10:03
  • 1
    No, you can't. Just you can assign to var every one div by ID, but nothing without this assignment. Commented Feb 5, 2015 at 10:03
  • 1
    This does work, but it's a bad idea. Commented Feb 5, 2015 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. Commented Feb 5, 2015 at 10:04
  • @Giorgio: It's an automatic global, because the element has an id. Commented Feb 5, 2015 at 10:04

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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` 

1 Comment

"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 without calling it "deprecated." I agree it's best to avoid using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.