Monday, March 27, 2023
HomeJavaScriptReminder about Internet Elements and Attributes

Reminder about Internet Elements and Attributes

After my submit yesterday about net part lifecycle occasions, I had an attention-grabbing dialog with Thomas Broyer on Mastodon. He introduced up a problem with net elements that I lined earlier than on this weblog, however because it was a really acceptable factor to debate instantly after yesterday’s submit, I assumed a little bit of repetition could be okay. And heck, I will take any probability to put in writing extra net part code because it provides me extra apply.

In order a reminder, yesterday’s submit particularly handled what code is greatest utilized in an internet part’s constructor versus the connectedCallback occasion. Particularly, it handled the use case of checking attributes and dealing with net part parts created by way of JavaScript. To be clear, I do not imply the definition of the online part, however creating an occasion of 1, like so:

let mc = doc.createElement('my-component');

Whereas I did not trouble setting a title in that instance, I might have carried out so like this:

let mc = doc.createElement('my-component');
mc.setAttribute('title','My title');

And it really works as anticipated. However this is an attention-grabbing query. What if in a while I alter the title? Think about this code:

setTimeout(() => {
	console.log('timer carried out, lets do that');
	mc.setAttribute('title','New title');
	console.log(`title for the mc is ${mc.getAttribute('title')}`);
}, 3 * 1000);

When run, what is going to it do? Try the CodePen beneath to see:

See the Pen WC Assessments (5) by Raymond Camden (@cfjedimaster) on CodePen.

As you possibly can see, it does not work. Bear in mind you possibly can open your browser’s console right here if you wish to see the messages. It should clearly say that the title attribute matches the replace, however that is what you will see mirrored within the DOM.

The nice (?) information is that that is fully anticipated and simply (for probably the most half) addressed. When defining an internet part, it is advisable to outline which attributes you care about it (when it comes to them altering) and write code to hear for these adjustments.

The primary half is straightforward:

“js static get observedAttributes() { return [‘title’] };

The subsequent half entails including an occasion handler named `attributeChangedCallback`:

attributeChangedCallback(identify, oldValue, newValue) {
	console.log(`altering the worth of ${identify} from ${oldValue} to ${newValue}`);

For those who do this, you will see that it is fired a number of instances. I had a “hard-coded” occasion of the part within the DOM and it’ll message that the title is altering from null to the hard-coded worth, reflecting the quick change of the online part being added to the DOM. Additionally, you will see this run with the occasion of the part created in JavaScript.

Now for the enjoyable half. The occasion handler wants to truly replace the show to replicate the brand new worth. Within the first iteration of my instance part, I skipped the Shadow DOM and simply wrote it out on to the primary DOM. Since I now have to (probably) replace the DOM a number of instances, I made two extra adjustments. I switched to the Shadow DOM and constructed a brand new methodology, updateDisplay, that handles updating the show. Here is your complete class:

class MyComponent extends HTMLElement {
	constructor() {
		console.log('constructor known as');

		const shadow = this.attachShadow({ mode: "open" });
		const div = doc.createElement('div');
		const h2 = doc.createElement('h2');

	connectedCallback() {
		console.log('related callback known as');
		if(!this.getAttribute('title')) this.setAttribute('title', 'No title');

	updateDisplay() {
		this.shadowRoot.querySelector('h2').innerText = `My Element: ${this.getAttribute('title')}`;
	static get observedAttributes() { return ['title'] };
	attributeChangedCallback(identify, oldValue, newValue) {
		console.log(`altering the worth of ${identify} from ${oldValue} to ${newValue}`);

Discover that updateDisplay simply makes use of querySelector to search out its h2 node and replace the textual content. Now our code that updates the title after a number of seconds will work accurately:

See the Pen WC Assessments (5) by Raymond Camden (@cfjedimaster) on CodePen.

For those who do not see the change, simply click on the “Rerun” button on the underside proper. Anyway, as I mentioned, I’ve mentioned this earlier than, but it surely positively tripped me up the primary time I bumped into it so hopefully this helps others!

Picture by Chris Lawton on Unsplash



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments