1

I have a snippet of code here

<div id="pTagId" >some content</div>

<button onclick="console.log(document.getElementById('pTagId').innerHTML);">button1</button>

<button onclick="console.log(pTagId.innerHTML);">button2</button>

In the first button I'm using document.getElementById to get the tag object. In the second button I'm directly using pTagId without document.getElementById and it also works.

is it reliable to use pTagId directly without document.getElementById? If yes what is the need of document.getElementById?

caramba
  • 21,963
  • 19
  • 86
  • 127
RRadley
  • 333
  • 3
  • 7
  • @PrashantPimpale that is the `id` of `div` and it prints the tag object. – RRadley Jan 30 '19 at 14:28
  • 1
    I've added `.innerHTML` and created a code snippet out of your sample so people can run the code and see what happens, hope that helps, if you don't like it you can remove it again – caramba Jan 30 '19 at 14:33

1 Answers1

1

getElementById() is the right way to do it.

There are some browsers that make a global variable by the same name as the element id so that may be why it was somehow working, but you should not rely on that.

Hannes Schneidermayer
  • 4,729
  • 2
  • 28
  • 32