useChildren
A reactive array of the host's direct light DOM children that match a selector. Used by components that take <option>-like children.
useChildren(selector: string, attributes?: string[]): Element[]const options = useChildren("option", ["value", "label", "disabled"]);
const menu = useState({
get items() {
return options.map((option) => ({ value: option.value, label: option.label }));
},
});Parameters
| Parameter | Type | Default | Meaning |
|---|---|---|---|
selector |
CSS selector | required | Which direct children to include (child.matches(selector)) |
attributes |
string[] |
[] |
Attribute names to watch on the children and their descendants |
Updates
The array is refreshed when:
- children are added, removed or reordered (anywhere in the light DOM subtree),
- text inside them changes,
- one of the listed
attributeschanges on a descendant, - a child REALM component finishes mounting, so its props can be read.
Watching stops when the element is removed.
Example
Enabled:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>useChildren demo</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/ui@alpha/dist/theme.css">
<script type="module" src="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.js"></script>
</head>
<body>
<import-element from="https://cdn.jsdelivr.net/npm/@realmorg/ui@alpha/components/button.html"></import-element>
<import-element from="./option-count.html"></import-element>
<option-count>
<option>Small</option>
<option>Medium</option>
<option>Large</option>
</option-count>
</body>
</html><custom-element name="option-count">
<script>
const options = useChildren("option", ["disabled"]);
const view = useState({
get enabled() {
return options.filter((option) => !option.disabled).map((option) => option.textContent).join(", ");
},
});
function toggleLast() {
host.lastElementChild.toggleAttribute("disabled");
}
</script>
<p>Enabled: <slot name="#view.enabled"></slot></p>
<ui-button variant="outline" onclick="toggleLast()">Toggle the last option</ui-button>
</custom-element>