简体   繁体   中英

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?

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM