Querying All Object Instances

Published: Wednesday, July 6, 2022

Greetings, friends! As part of the Console Utilities API in Google Chrome, we get access to the queryObjects function in the DevTools console. This function returns an array of objects that were created with the specified constructor. Let's look at an example.

javascript
Copied! ⭐️
queryObjects(HTMLElement);

If we run the above code in the Chrome DevTools console, then we'd see an array of all HTML elements on the current page. The queryObjects function will look for all objects that were created using the HTMLElement constructor. Since the browser creates an HTML Document Object Model (DOM), it will create instances using the HTMLElement constructor.

Let's use queryObjects to grab a list of all Events that are created using the Event constructor or interface.

javascript
Copied! ⭐️
queryObjects(Event);

After running a query on all Event instances, we get back an array of 76 items! It's interesting to see what events are available to us in the browser without having to dig through documentation. Here are a few events that are logged to the console after running queryObjects(Event).

javascript
Copied! ⭐️
Array(76)
0: TransitionEvent {Symbol(Symbol.toStringTag): 'TransitionEvent', constructor: ƒ}
1: AnimationEvent {Symbol(Symbol.toStringTag): 'AnimationEvent', constructor: ƒ}
2: ProgressEvent {Symbol(Symbol.toStringTag): 'ProgressEvent', constructor: ƒ}
3: RTCPeerConnectionIceErrorEvent {…}
4: RTCErrorEvent {Symbol(Symbol.toStringTag): 'RTCErrorEvent', constructor: ƒ}
...

We can even use queryObjects to find all instances of custom classes we create in JavaScript. Let's create a class called Person with a constructor that accepts a firstName and lastName property.

javascript
Copied! ⭐️
class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

We can create instances of this class and log all of them to the console with queryObjects.

javascript
Copied! ⭐️
const ash = new Person('Ash', 'Ketchum');
const nathan = new Person('Nathan', 'Vaughn');

queryObjects(Person);

When queryObjects(Person) is executed, it should return an array of all objects created using the Person constructor.

javascript
Copied! ⭐️
[
  Person {firstName: 'Ash', lastName: 'Ketchum'}
  Person {firstName: 'Nathan', lastName: 'Vaughn'}
]

Pretty cool! If we had a complex app and wanted to see a list of all instances of a class, the queryObjects function would definitely come in handy! There are many Web APIs available to us in the browser, and they contain a lot of different interfaces. The HTMLElement interface was just one of them. Try inserting other interfaces into the queryObjects function to see what you can find!