Custom elements

A custom element specification lets you create a custom HTML tag that can be used as its own HTML tag on the page. In order to achieve this, we need to first write a class with the functionalities associated with that HTML element, and then we need to register it so that the browser understands what this HTML tag is, and how it can be used on the page. 

If you are someone who is new to the concept of classes in JavaScript, here is how you can create a class:

class myClass {
constructor() {
// do stuff
}
}

Pretty simple, right? Let's use the same class structure to create our custom element class, say HelloWorld:

class HelloWorld extends HTMLElement {
constructor() {
// very important
// needed in every constructor
// which extends another class
super();

// do magic here
this.innerText = 'Hello World';
}
}

In the preceding code, our custom element class is called HelloWorld and it is extending interface from the HTMLElement class, which represents how an HTML element should work on a page. So, HelloWorld now knows what click events are, what CSS is, and so on, simply by extending HTMLElement.

Inside this class, we have the constructor() method, which gets called as soon as a new instance of this class is created. The super() function needs to be called in order to correctly instantiate the properties of the extended class.

The preceding code simply creates the element class definition. We still need to register this element. We can do so by writing the following code:

customElements.define('hello-world', HelloWorld);

What it does is register the class HelloWorld by defining it using the define() interface in the customElements interface; hello-world is the name of the custom element that is going to be available on the page.

Once this is defined, you can used the custom element by simply writing the HTML tag as following:

<hello-world><hello-world>

When this code is run on a browser, it will render the text, Hello World.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.190.167