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