I aim to generate <slot>
s for each child element. For instance, I have a menu and I intend to place each child inside a <div>
with a item
class.
To achieve this, I have devised a small utility function for mapping the children:
export function ChildrenMap(el: LitElement, map: (el: HTMLElement, index: number) => TemplateResult): TemplateResult[] {
console.log(el.children.length) // It returns 0 in browsers like Google Chrome and possibly Edge.
return (Array.prototype.slice.call(el.children) as HTMLElement[])
.map(map);
}
Subsequently, I utilize this function in the render method:
render() {
return html`
<nav>
${ChildrenMap(this, (ele, index) => {
let id = ele.id ? ele.id : `item-${index}`;
ele.setAttribute('slot', id);
let klass = 'item';
if (this.selected && this.selected == index) {
klass += " selected";
}
return html`
<div class="${klass}" data-index="${index}">
<slot name="${id}"></slot>
</div>`;
})}
</nav>
`;
}
While this code operates smoothly in FireFox, in Google Chrome, the element is devoid of children during rendering, leading to an empty <nav>
element. Can anyone clarify why the element has no children at the moment of rendering?
If I am approaching this incorrectly, are there any alternate methods to accomplish this task?
Thank you