A554551N
A554551N

Reputation: 155

JS Variable Can Be Seen In Chrome Console, But Isn't Explicitly Defined

Noob Question of the day:

I have created a web page with an HTML element that has an ID. This web page uses jquery and a handful of other libraries.

ex) <div id="personList ">

In the .js used by the page I manipulate the element using jquery and it's #id as the selector - works like a charm.

ex) $("#personList")...

In the Chrome console simply typing in personList displays the HTML element and its attributes. I would have assumed it would not - as there's no javascript variable created with that name...

Is this because:

  1. Chrome is smart enough to recognize the element in the DOM and assumes I was referring to it?
  2. Something automagically created a variable out of the element and put it into the global (or other near-global) scope ?
  3. Something else entirely?

I am sure this has been answered somewhere, and is likely well documented, but I'm at a loss when trying to find it with my keywords.

Upvotes: 1

Views: 338

Answers (2)

Marcos Casagrande
Marcos Casagrande

Reputation: 40394

DOM element IDs are global variables.

From the HTML5 standard

the value of the id content attribute for all HTML elements that have a non-empty id content attribute and are in a document tree with window's browsing context's active document as their root.

So if we have: <div id="bar"></div>, you can access that element through: window.bar

console.log(window.test);
window.test.innerHTML = 'amazing';
<div id="test"></div>

Relying on this this "feature" can be the cause of a lot of bugs, so I recommend to never use it. Take the following example:

window.that.innerHTML = 'It works';

// some library declares `that` as a global variable
window.that = {};

// This won't work, since window.that no longer references the DOM element
window.that.innerHTML = 'It no longer works';
<div id="that">Evil div</div>

Upvotes: 2

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

Due to reasons best lost in history, elements with an ID element become attached to the global object and acts like global variables.

They can be shadowed by declaring a variable (with let, const or var) globally.

When you type personList in the console, it access window.personList.

This is not a behavior that should be relied on anymore but remains to keep backwards compatibility with some ancient code.

Upvotes: 1

Related Questions