- From: Ryosuke Niwa <notifications@github.com>
- Date: Tue, 19 Mar 2019 21:51:28 +0000 (UTC)
- To: w3c/webcomponents <webcomponents@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
- Message-ID: <w3c/webcomponents/issues/789/474598795@github.com>
Anyway, if you wanted to do something with every child custom element in a parent, you'd do something like this. I didn't debug too much but seems to mostly work.
```html
<!DOCTYPE html>
<html>
<body>
<custom-parent><div></div><custom-child id="c1"></custom-child><span></span></custom-parent>
<script>
class CustomParentElement extends HTMLElement {
isChildElementToWatch(node) { return node.localName == 'custom-child'; }
constructor() {
super();
const nodesToCheck = [];
for (let node = this.firstChild; node; node = node.nextSibling) {
if (!this.isChildElementToWatch(node))
continue;
if (node.matches(':defined'))
this.didConnectCustomChild(node);
else
nodesToCheck.push(node);
}
Promise.resolve().then(() => {
for (const node of nodesToCheck) {
if (node.matches(':defined'))
this.didConnectCustomChild(node);
}
});
const observer = new MutationObserver((recordList) => {
const addedNodes = new Set;
for (const record of recordList) {
for (const node of record.addedNodes) {
if (this.isChildElementToWatch(node))
addedNodes.add(node);
}
// This skips all the elements that got temporaily inserted and then removed.
// Delete this code if you wanted to observe all children ever got inserted.
for (const node of record.removedNodes) {
if (this.isChildElementToWatch(node))
addedNodes.delete(node);
}
}
for (const node of addedNodes)
this.didConnectCustomChild(node);
});
observer.observe(this, {childList: true});
}
didConnectCustomChild(child) {
console.log(child);
}
}
customElements.define('custom-parent', CustomParentElement);
class CustomChildElement extends HTMLElement { }
customElements.define('custom-child', CustomChildElement);
</script>
<custom-parent><div></div><custom-child id="c2"></custom-child><span></span></custom-parent>
<script>
const parent = document.createElement('custom-parent');
parent.appendChild(document.createElement('custom-child')).id = 'c3';
parent.innerHTML = '<custom-child id="c4"></custom-child>';
</script>
</body>
</html>
```
--
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/webcomponents/issues/789#issuecomment-474598795
Received on Tuesday, 19 March 2019 21:51:50 UTC