4

I noticed that when I assign some id to a DOM element, I can then reference that element in javascript, just by treating its id as a javascript variable name.

For example

console.log(myDiv);
<div id="myDiv">some text</div>

Is there a difference between referencing a DOM element with document.getElementById(id) and just its id?

Can I expect this behaviour in all browsers?

Scruffy
  • 444
  • 1
  • 6
  • 13
  • 3
    For a long time Firefox was a holdout and did *not* behave that way, but now it does. In my opinion it was an absolutely terrible idea in the first place for Internet Explorer to implement, but that's where we are. – Pointy Feb 11 '18 at 15:22
  • 3
    Using direct access to the dom element by id is not a safe way. Moreover your code debugging will be more difficult. Also if you will have the same variable name in the function scope, your script first of all will use such variable – Sviat Kuzhelev Feb 11 '18 at 15:24

0 Answers0