Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
123
Help us understand the problem. What is going on with this article?
@nakajmg

HTML内でIDをつけた要素はJavaScriptのグローバル変数に格納される

More than 5 years have passed since last update.

id属性に値を設定すると、設定した値の変数がwindowオブジェクトのプロパティとして作られてJSからアクセスできる。

<body>
  <div id="test">てすと</div>
  <div id="global">ぐろーばる</div>
  <script>
    console.log('test' in window);          // true
    console.log('global' in window);        // true
    console.log(test === window.test);      // true
    console.log(global === window.global);  // true
  </script>
</body>

id.gif

こんな仕様になってたの知らなかった。

(HTMLの解析後に作られるのでDOMの準備が出来る前に参照するとエラーになる)

Command Line APIとかで人様のサイトを調べるときにページ内の要素のidに<div id="copy">とか振ってあると上書きされてAPIが使えなくなってちょっと邪魔。


参考

DOM: element IDs are global variables

123
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
nakajmg
フロントの人。JavaScript/CSS/HTML

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
123
Help us understand the problem. What is going on with this article?