Chrome console.log(elementID) outputs the element in the console

江枫思渺然 提交于 2019-12-20 02:46:12

问题


<input type="text" placeholder="Password" id="password" name="password" />
<script>
    console.log(password);
</script>

The code above outputs the following in the console:

<input type="text" placeholder="Password" id="password" name="password">

Noticed this when I outputted a variable password and noticed the HTML was prepended. Is that normal behaviour? What do we have getElementById for in that case?


回答1:


Legacy behaviour is to define all elements with IDs (and names, I think) as properties of window. Therefore, window.password (or just password) could in theory be used as a shortcut for getElementById. However as soon as you define a variable with that same name, you get unpredictable behaviour.

This is one reason why global variables are bad. Always define your variables locally with var.




回答2:


Getting an element using window[element id] or window[element name] is standard behavior implemented by all modern browsers since Firefox 14. I'll refer you to a few posts on the subject. As you'll find in most posts about the matter, use of the behaviour is not recommended and generally slower as browsers optimize .getElementById and checking if a variable is an id or name is the lowest priority in global scope.

  • Do DOM tree elements with ids become global variables?
  • Can I use the id of an HTML element as a variable in JavaScript?


来源:https://stackoverflow.com/questions/19918588/chrome-console-logelementid-outputs-the-element-in-the-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!