Skip to content

getInstances ​

ts
getInstances<T extends Base = Base>(name: string, root?: ParentNode): T[]
getInstances<T extends Base = Base>(el: Element): T[]

Every instance that exists for a component name, mounted or not, in DOM order — or every instance on one element, in mount order.

Usage ​

ts
import { 
getInstances
} from '@studiometa/js-toolkit';
const
section
=
document
.
querySelector
('section')!;
getInstances
('Dialog'); // every Dialog in the document
getInstances
('Dialog',
section
); // every Dialog built in a region
getInstances
(
section
); // everything on one element

Reach for it when the result is counted or inspected. When it is going to be used, prefer getMountedInstances() — every instance in that list has run mounted() and has not yet run unmounted().

The two overloads ​

ts
(name: string, root?: ParentNode): T[]
(el: Element): T[]
  • The name form searches the descendants of root, which defaults to the document. root is a ParentNode and the call is querySelectorAll, so it never matches root itself.
  • The element form reads the element's instance map directly and never consults the DOM, so it answers for a detached element as readily as for a connected one. The name form cannot: document.querySelectorAll() does not see a detached element. Pass the detached root as root when a name lookup has to reach inside it.

How the narrowing works ​

selectorFor(name) over-matches on purpose — it lists the responsive spellings of data-component too — and the instance-map read is what removes an inactive declaration, because a breakpoint-withdrawn component is destroyed and deleted from the map.

A matching element with no instance is skipped, and that is the whole narrowing. There is no mount filter, because it never did that work.

Where the instances live ​

An element publishes its instances under Symbol.for('@studiometa/js-toolkit/instances'). That map is not public API; these four lookups are, and between them they express every read it answers. In a console:

js
$0[Symbol.for('@studiometa/js-toolkit/instances')];

The element overload exists rather than a second export because both forms answer "which instances are there" and the argument picks the scope — and it keeps the map read in one place, which matters more now that the key is a symbol and no longer spellable as el.__base__.

MIT Licensed