Radiant0.3.0

createQuery

createQuery creates a lazy DOM query accessor bound to a host element. It is the functional equivalent of the @query decorator, designed for vanilla JS usage or cases where decorators are not available.

Usage

import { RadiantElement } from '@ecopages/radiant';
import { createQuery } from '@ecopages/radiant/helpers/create-query';
 
class UserProfile extends RadiantElement {
	#avatar = createQuery<HTMLImageElement>(this, { ref: 'avatar' });
	#items = createQuery<HTMLElement[]>(this, { selector: '.item', all: true });
 
	get avatar() {
		return this.#avatar.value;
	}
 
	get items() {
		return this.#items.value;
	}
}
 
customElements.define('user-profile', UserProfile);

The accessor returns an object with a .value getter. Each read of .value runs the query unless caching is enabled.

Parameters

createQuery<T>(host, options) accepts:

ParameterTypeRequiredDescription
hostHTMLElementYesThe element to query within.
optionsQueryConfigYesQuery configuration (see below).

QueryConfig

FieldTypeRequiredDescription
selectorstringOne of selector/refCSS selector to match elements.
refstringOne of selector/refValue of data-ref attribute to match.
allbooleanNoReturn all matching elements instead of the first (default: false).
cachebooleanNoCache the query result (default: false).

Return Value

Returns a QueryResult<T> object with a single .value getter:

  • When all is false: returns T | null.
  • When all is true: returns T (an array), or an empty array if nothing matches.

Caching

By default, every .value read re-runs the query. Set cache: true to store the result and return it on subsequent reads.

const items = createQuery<HTMLElement[]>(host, {
	selector: '.item',
	all: true,
	cache: true,
});
 
items.value; // queries the DOM
items.value; // returns cached result

Learn More