Where is the variable containing the element with the id stored?

This question ( Element available with an identifier ) indicates that if an element has an identifier, you can access it by the name of the variable based on this identifier. I was intrigued because I saw this variable available when developing using Visual Studio 2010. I did some testing out of curiosity and it turned out that document.getElementById() is still faster than using the variable name. So, I started looking for a window, believing that it should be in window["idName"] , debugging console.log(window) , and could not find where the variable was actually saved.

When an element is defined in html with <div id="foo"> , it is available in javascript with the variable foo (I do not suggest using this, this is bad practice). Where is this variable stored?

+7
source share
1 answer

This is non-standard behavior. Where (and if) it is stored until implementation.


Using Firefox 15 on Linux, I had to go through 2 prototype objects to find the actual object. I ran this code on this StackOverflow page and got the result true .

 Object.getPrototypeOf(Object.getPrototypeOf(window)).hasOwnProperty("hlogo"); 

On Chrome on Linux, it was on par.

 Object.getPrototypeOf(window).hasOwnProperty("hlogo"); 

I was really surprised to see it in Firefox, but since Chrome followed the Microsoft pattern, I think Firefox must have felt the need to follow suit.


If you don’t know how deep the prototype chain is, you can start the loop and add various objects to the array or just work with the objects in the loop.

 var protos = [], obj = window; while (Object.getPrototypeOf(obj) !== null) { obj = Object.getPrototypeOf(obj); protos.push(obj); } alert("The object had " + protos.length + " prototype objects"); 
+7
source

All Articles