rich22 rich22 - 5 months ago 16
HTML Question

document.getElementbyId vs. shorthand (Id.someMethod)

Is there any advantage to writing out

document.getElementById
when you can just use the shorthand
Id.something
? I'm interested because I see some code online in my tutorials declaring variable
x
equals to
document.getElementById
, and then them using that variable, instead of just using the shorthand:

Example:

<code>
var timeDisplay = document.getElementById("time");
timeDisplay.innerHTML = message;
</code>

VS.

<code>
time.innerHTML = message;
</code>

Answer

Expanding on my comment, you should never use the "shorthand" because it is dangerous and confusing.

It is dangerous because someone else can defined the window.time property before your code gets executed, and now your entire code breaks:

// some one put this in the global scope
var time = new Date();

// your code
time.innerHTML = message; // nope!

https://jsfiddle.net/DerekL/6yz8j7dx/

It isn't even about subjective choices. It's that you should almost never do time.something.


Bonus example on why it is confusing:

<div id="history"></div>

history.textContent = "Will it work?";

Guess what will happen?