[Suggestion] Using slots with a LightDOM components.
It is possible to use LightDOM instead of ShadowDOM and still manage `<slot>` mechanics. Sometime it might be prefered to have custom elements that do not use the ShadowDOM.
Here is the utility function for it ([original source](https://tritarget.org/#LightDOM%20Utility) mine with tests/demo).
```js
/**
* LightDOM mimic of the slot mechanics used in ShadowDOM.
* @param {Element} target
* @param {Element} content
*/
function appendWithSlotableContent(target, content) {
target.querySelectorAll('[slot]').forEach(node => {
let slotName = node.getAttribute('slot');
content.querySelector(`slot[name="${slotName}"]`)?.after(node);
});
content.querySelector('slot:not([name])')?.after(...target.childNodes);
content.querySelectorAll('slot').forEach(node => node.remove());
target.append(content);
}
class FooBar extends HTMLElement {
connectedCallback() {
let { content } = document.getElementById('foo-bar')
appendWithSlotableContent(this, content.cloneNode(true));
}
}
customElements.define('foo-bar', FooBar);
```
1 条评论