Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 249
user2019515 Avatar asked Mar 22 '23 16:03

user2019515


1 Answers

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?
like image 178
megawac Avatar answered Apr 07 '23 18:04

megawac