Jsilvermist
Jsilvermist

Reputation: 501

List Variables and Methods on DOM Object

How would I find out what variables and methods are on a DOM Object? In the example below, how do I find out that div#main has a variable greeting, and a method greet?

(Preferably without using an external library.)

var main = document.querySelector('#main');

main.greeting = 'Hello Meep!';

main.greet = function() {
  alert(this.greeting);
}

main.greet();
<div id="main">
  ...
</div>

Upvotes: 0

Views: 217

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075149

On browsers that allow it with DOM elements, you can use Object.keys or for-in to get an array of the enumerable properties:

console.log(Object.keys(main));

That works on a wide range of modern browsers, but note that browsers are not required to allow you to introspect DOM elements that way, so if you rely on it, be sure to test in your target browsers.

If you want non-enumerable properties as well as enumerable ones, you could try Object.getOwnPropertyNames(main) rather than Object.keys(main).

Example:

var main = document.querySelector('#main');

main.greeting = 'Hello Meep!';

main.greet = function() {
  alert(this.greeting);
}

main.greet();

var p = document.createElement('p');
p.appendChild(document.createTextNode(
  Object.keys(main).join(", ")
));
document.body.appendChild(p);
<div id="main">
  ...
</div>

Upvotes: 1

Related Questions