Mankament Gra Mankament Gra - 1 month ago 5
Javascript Question

How can i get window property from element

<body>
<h1 id="a">Site 3</h1>

<script>

var arr = []

for(var i in window)
{
arr.push(i)
}
console.log("a" in window)// true
console.log(arr)// dont have property a why?!
</script>

</body>


But when i run console.log(arr) i dont have a in the arrey, why?

Answer

The things accessible on window are not necessarily "own" properties of window and (this is the significant bit) are not necessary enumerable. for-in only visits enumerable properties (both "own" and inherited).

On Chrome, for instance, the automatic a global is a property of the prototype of the prototype of window, and it's marked as non-enumerable:

var o = window;
var where = "window"
while (o && !Object.getOwnPropertyDescriptor(o, "a")) {
  where = "prototype of " + where;
  o = Object.getPrototypeOf(o);
}

console.log(where);
console.log(Object.getOwnPropertyDescriptor(o, "a"));
<div id="a"></div>

Looks like it's in the same place on Firefox.

The exact semantics of how named access is achieved isn't dictated, so long as in works and window.a works.