LoginSignup
141
136

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-06-01

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

141
136
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
141
136