最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chrome console.log(elementID) outputs the element in the console - Stack Overflow

programmeradmin0浏览0评论
<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?

Share Improve this question asked Nov 12, 2013 at 0:15 user2019515user2019515 4,5032 gold badges32 silver badges42 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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 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.

发布评论

评论列表(0)

  1. 暂无评论