Types of custom elements

Now that you have understood how we can register custom elements, it is time we looked deeper into the type of custom elements. Based on the type of requirement, we can create two types of custom elements: 

  • Autonomous custom element: Any element that can be used by itself, without depending on another HTML element can be considered an autonomous custom element. In technical terms, Any custom  hat extends HTMLElement is an autonomous custom element.

Let's have another example of an autonomous custom element. Let's create a SmileyEmoji element that shows a smiley emoji. Here is what it looks like:

class SmileyEmoji extends HTMLElement {
constructor() {
super();
// let's set the inner text of
// this element to a smiley
this.innerText = '';
}
}

customElements.define('smiley-emoji', SmileyEmoji);

This registers the smiley-emoji custom element, which can be used as follows:

<smiley-emoji></smiley-emoji>
  • Customized built-in element: This type of custom element can extend the functionality of an already existing HTML tag. Let's create a custom element that extends HTMLSpanElement instead of HTMLElement. And its functionality is, say, it needs to add a smiley emoji at the end of the custom element:
class AddSmiley extends HTMLSpanElement {
constructor() {
super();

// lets append a smiley
// to the inner text
this.innerText += '';
}
}
customElements.define('add-smiley', AddSmiley, { extends: 'span' });

Now, if you have the following HTML, this will add the smiley to the end of the text Hello World:

<span is="add-smiley">Hello World</span>

Try running the code for autonomous custom elements and customized built-in elements on a browser, or CodePen, or JSFiddle. The class and registration code will be in the JavaScript block and the rest will be in the HTML block.

Notice the difference in registration code for <smiley-emoji> and <add-smiley> custom elements. The second one uses an extra parameter that specifies what it is extending.

You can check whether a custom element is already defined or not with the help of the following code:

customElements.get('smiley-emoji');

It will either return undefined if it has not been registered, or will return the class definition, if it has been registered. This is a very helpful statement in large projects because registering an already registered custom element will break the code.

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

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