How can I enumerate through Javascript objects like HTMLElement? [duplicate]

StackOverflow https://stackoverflow.com/questions/23519402

  •  17-07-2023
  •  | 
  •  

Question

I'd like to enumerate through all the global objects. This includes ones like HTMLElement, SVGAnimatedPreserveAspectRatio, and CameraControl. All of the answers I've seen for this problem have you iterating through window or the global object (obtained via tricks like this outside a namespace). However these tricks do not list the element, even though it is contained in window!

Here's some console log, but if you put it in a test .html page, you get the same result.

> HTMLElement
[object Function]
> window['HTMLElement']
[object Function]
> 'HTMLElement' in window
true
> for(var name in window){if(name == "HTMLElement")console.log('Found it!');}
undefined
> for(var name in window){if(name == "sessionStorage")console.log('Found it!');}
"Found it!"

How can I enumerate through all the global objects?

Était-ce utile?

La solution

You can iterate over all global objects like this:

var arr = Object.getOwnPropertyNames(window);
for(var i = 0; i < arr.length; i++){
   window[arr[i]]; // do something
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top