document.getElementbyId vs. shorthand (Id.someMethod)

前端 未结 1 1772
南笙
南笙 2021-01-21 23:33

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 cod

相关标签:
1条回答
  • 2021-01-22 00:16

    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?

    0 讨论(0)
提交回复
热议问题