admin管理员组文章数量:1410697
<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?
<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?
2 Answers
Reset to default 4Getting 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 remended 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 bee global variables?
- Can I use the id of an HTML element as a variable in JavaScript?
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
.
本文标签: javascriptChrome consolelog(elementID) outputs the element in the consoleStack Overflow
版权声明:本文标题:javascript - Chrome console.log(elementID) outputs the element in the console - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745066633a2640560.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论