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

admin2025-04-19  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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745066635a283026.html

最新回复(0)