skip to content
dz

Back to the article 路 Zur眉ck zum Artikel (Deutsch)

Example 02: The same element, fixed

Rule 1: Don't touch attributes or children in the constructor

The text is set in the attributeChangedCallback, which runs for the attribute from the HTML as well as for the one set with setAttribute().

How to try it

  1. Look at the live example below the output boxes.
  2. Both elements show their name: "馃憢 Hello, Ada!" and "馃憢 Hello, Grace!". Compare with example 01.
Console output mirrored from console.log() and errors on this page, the same text as in the developer tools

The constructor only creates the shadow root, the text comes from the attribute callback.

Live example

Source

<p><hello-name name="Ada"></hello-name></p>

<script type="module">
	class HelloName extends HTMLElement {
		static observedAttributes = ['name'];

		constructor() {
			super();
			this.attachShadow({ mode: 'open' });
		}

		attributeChangedCallback(name, oldValue, newValue) {
			this.shadowRoot.textContent = `馃憢 Hello, ${newValue ?? 'stranger'}!`;
		}
	}

	customElements.define('hello-name', HelloName);

	const created = document.createElement('hello-name');
	created.setAttribute('name', 'Grace');
	document.body.append(created);
</script>