Get the child elements inside a parent node.
Let's suppose we have a few containers with checkboxes in each of them. We don't know how many checkboxes will be in each container at the final design.
Each container has a "select all" named checkbox that allows us to check on/off all checkboxes into a current target container.
We want to provide a good abstract solution for avoiding hard coding of elements' ID. And ensure scaling for any count of the elements in the future.
And here, my solution on how to implement a child query selector for Velo.
For Example:
We have two groups with checkboxes:
And when we click by a checkbox "All" we need to switch all checkboxes in target group. For example like this:
$w.onReady(() => {
$w('#checkboxAllYellow').onChange((event) => {
findIn('#boxYellow').all('Checkbox').checked = event.target.checked;
});
$w('#checkboxAllBlue').onChange((event) => {
findIn('#boxBlue').all('Checkbox').checked = event.target.checked;
});
});
The next snippet of code it's a realization of this selector.
We can find all Checkbox in # boxBlue
and
We can find all Checkbox in # boxYellow
findIn("#ID").all("Type")
/**
* @param {$w.Node} element
* @param {string} parentId
* @returns {boolean}
*/
const hasParent = (element, parentId) => {
while (element) {
element = element.parent;
if (element?.id === parentId) {
return true;
}
}
return false;
};
/**
* @param {WixElementSelector} selector
*/
export const findIn = (selector) => {
const parentId = selector.replace(/^#/, '');
return {
/**
* @template {keyof TypeNameToSdkType} T
* @param {T} type
* @returns {TypeNameToSdkType[T]}
*/
all(type) {
/** @type {any} */
const elements = $w(type);
const ids = elements.reduce((acc, element) => {
if (hasParent(element, parentId)) {
acc.push(`#${element.id}`);
}
return acc;
}, []);
return $w(ids.join(','));
},
};
};
I described in detail how it works in my blog post.
Welcome to reading:
This is great! Wish I found it a month ago lol