Christoph Wissing
Christoph Wissing

Reputation: 403

Can't list window.document properties - why?

Running this JavaScript lists in Firefox 60.2 only one property ("location"), but there are many others, like "document.title" etc.

window.console.log("List props: " + Object.keys(window.document).sort().join(' / '));

Why is it this way? Safety? How is this done technically? How can I list all properties?

Upvotes: 3

Views: 74

Answers (3)

Ahmed Bajra
Ahmed Bajra

Reputation: 401

I couldn't find an official reason for it not working with window.document but it seems you can reproduce this behavior with other variables as well. The issue seems to be Object.keys() not returning everything from these variables.

If you're still trying to get all properties of document, you can still use

var props = [];
for(var prop in window.document) {
    props.push(prop);
}
console.log("List props: " + props.sort().join('/'));

Which will do the exact same thing as your approach.

Upvotes: 0

Manos Kounelakis
Manos Kounelakis

Reputation: 3181

The reason is that Object.keys() returns returns an array of strings that represent all the enumerable properties of the given object. Try this to see which properties of document are enumerable

for(let key in document){
  let isEnumerable  = document.propertyIsEnumerable(key);
  console.log(`docment['${key}'] isEnumerable?:${isEnumerable}`);
}

However as the previous answer has stated you can use a for-in loop to get all properties in an array sort them and join them

Upvotes: 0

joews
joews

Reputation: 30340

Object.keys(o) returns the own, enumerable properties of o.

  • Own: properties defined directly on o, not on its prototype chain:
  • Enumerable: a flag that controls if a given property is included when listing an object's properties.

In this case most of the keys you expect are defined on another object in in document's prototype chain:

document.hasOwnProperty("title"); // false
document.__proto__.__proto__.hasOwnProperty("title"); // true
document.__proto__.__proto__.propertyIsEnumerable("title"); // true

You can use a for... in loop to find the enumerable properties that are defined on an object or its prototype chain:

for (let key in window.document) {
  console.log(key);
}

Upvotes: 2

Related Questions