Help us understand the problem. What is going on with this article?

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

nakajmg
フロントの人。JavaScript/CSS/HTML
http://nakajmg.github.io/
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした