skip to content
dz

Back to the article · Zurück zum Artikel (Deutsch)

Example 06: Callback of a removed child (example from the specification)

Rule 3: Don't wait for callbacks with setTimeout

If the connectedCallback of a parent removes its child, the child's connectedCallback still runs. The example comes from the HTML specification (section 4.13.2).

How to try it

  1. Open the console of the developer tools (F12, Cmd+Opt+I on a Mac). The "Console output" box on this page shows the same lines.
  2. The output says isConnected = false.
Console output mirrored from console.log() and errors on this page, the same text as in the developer tools
Expected output what the lines above should say
CChild connectedCallback: isConnected = false

Live example

Source

<script>
	class CParent extends HTMLElement {
		connectedCallback() {
			this.firstChild.remove();
		}
	}
	customElements.define('c-parent', CParent);

	class CChild extends HTMLElement {
		connectedCallback() {
			console.log('CChild connectedCallback: isConnected =', this.isConnected);
		}
	}
	customElements.define('c-child', CChild);

	const parent = new CParent();
	const child = new CChild();
	parent.append(child);
	document.body.append(parent);
</script>