$w('Page') issues with Chrome et al

I have code that gathers page elements by type - something like:

// Create arrays of page element IDs.
let pageElementIds = $w('Page').children;

function findImageElementIds(element) {
  let regex = /imTag/;
  return regex.test(element.id);
}
  
let imageElementIds = pageElementIds.filter(findImageElementIds);

This code works perfectly fine in Firefox, yet when I try to run it in Chrome, Edge, or Vivaldi, I get a series of console errors that seem to boil down to:

Typerrror: Cannot read property 'filter' of undefined. 

Given that the array filter method is supported by all browsers, I can only assume that the issue lies with the way that $w(‘Page’) is being interpreted. Can anyone shed light on what might be going on here? The fact the code works perfectly in Firefox but none of the other browsers really has me confused.

Anyone? I will make it even simpler:

let documentElementIds = $w("Document").children;
console.log(documentElementIds);

let pageElementIds = $w('#page1').children;
console.log(pageElementIds);

Why does this code produce the following errors in Chrome but not Firefox?

Is there another way to compile an array of specific page elements that does not use the obviously broken code above?

Have you put it inside $w.onReady() ?

Aw darn it - and I remember reading somewhere that you were supposed to put all code that uses $w() inside onReady too. Thanks very much J.D.

You’re welcome.

BTW.
You can have code outside the $w.onReady() if it doesn’t contain $w or if it is in the exported event handler that you set via the property panel.