1. What are Basics of Custom HTML Tags or Elements?
It is very fascinating to know that a developer can write his own custom HTML tag alongside any regular HTML5 element. While reading the markup of a document, reading <header> and <footer> tags depict that these elements are for the header and footer of that document respectively. This is called semantic HTML, and any HTML5 semantic tag has the meaning of its use. Also, the custom HTML5 elements allow the developer to add his own styles via CSS stylesheets and functionality using JavaScript programming.
Similarly, just like semantic HTML elements, we can write our own custom HTML tags that will portray some meaning as per their use in the document. These elements basically allow us to create new tags, extend the previous ones and make reusable components. Hence there are two types of custom HTML elements or tags.
- Create New HTML Elements
- Extend Existing HTML Elements
The example below depicts how custom tags in HTML may look like, and how to use them.
Example
<new-customer> <customer-name>John Doe</customer-name> <customer-age>40 Years</customer-age> </new-customer>
1.1. What are Web Components?
Web components are a collection of APIs on any web platform that allows the creation and utilization of custom HTML tags or elements. Basically, we create reusable and encapsulated components for the web using the web components. The web components act as a standard for newly created HTML5 tags just like any other element. There are basically four standards or specifications of web components.
- Custom Elements: Creating New Elements
- Shadow DOM: Tells how to use the style in markup
- ES Modules or HTML Imports: Adds functionality of JavaScript documents
- HTML Template: Sets the running behavior and time of markup
1.2. What is the Need for a Custom HTML Tag?
- There is always a deficiency and lack of functionality in the existing HTML tags.
- To cope with modern and up-growing HTML5 standards and to fulfill personal needs, the developer finds it easy to use custom HTML5 tags in their markup.
- Also, just think of <modal-contact>, <image-gallery>, <fancy-font>, etc. and you will love this idea of custom HTML5 elements.
- Moreover, using custom tags has revolutionized the HTML language and it has become more modern as a custom HTML5 element imparts new behaviors to newly designed markup.
- In this way, the difficulties with the old markup or deficiencies are fulfilled by designing new HTML tags.
1.3. Advantages of Custom HTML5 Tags
Custom HTML5 elements once created can be used and manipulated just like other HTML tags. Below are some advantages or benefits of using custom HTML elements.
- Reusability: The first benefit is reusability i.e write code once, and reuse the custom-created HTML tag or element as much as you want.
- Meaningful Tags: They add meaning to HTML markup from element to element.
- Descriptive Names: Each custom element tells its meaning from its name registered.
- Encapsulation: It means that each custom element holds its own private styling, properties, and methods, which are only available to that particular element.
- Easy Markup: It is far easy to read a markup containing these elements.
- Browser Support: All browsers support custom HTML elements including Internet Explorer.
- Style Management: CSS styling will be much more organized.
- Extensibility: We can further extend and customize the custom HTML tags using inheritance and composition.
2. Rules to Create Own Custom HTML Tags
2.1. Registered and Unregistered Custom HTML Elements
Creating your own custom HTML tags is always easy and fun. We can create over own custom HTML5 tag as fast as the below instance.
Example
<home-slider></home-slider>
In the above example, a custom element is used in the HTML. By default, it is an inline element and we can style it using CSS or attach different events via Javascript. However, it is unregistered and the HTML parser will not recognize it.
2.2. Why Do We Register Custom Elements?
Although, the tag in the above example produces results and works perfectly fine. The problem is that, whenever the parser reaches this tag, it will use the HTMLUnknownElement interface. Whereas, a registered and defined HTML tag uses an HTMLElement interface that is easily understood by the DOM and generates an object of that particular custom tag or element.
2.3. Rules to Create an HTML5 Custom Tag
- Since HTML elements have single-word names, the custom tags are a bit different from those
- There must be a dash - sign in the tag name e.g. <new-customer>
- This rule is strictly followed to help the parser distinguish normal HTML from newly formed tag
- Further, a tag once registered, cannot be defined again or a DOM error will occur
- Lastly, there is no possibility to formulate a singleton tag
- Hence, any new HTML tag must end with a closing tag i.e. <new-customer></new-customer>
2.4. Valid and Invalid Custom Tags
Following the above rules, there are some naming conventions to follow while defining a custom tag. Below are some examples of valid and invalid custom HTML tags.
Valid Names
- <new-element>
- <another-new-element>
- <a-z>
- <services-24>
- <sad-child-😓>
- <message-box>
- <s-⭐>
Invalid Names
- <customtag>
- <another_happy_ta>
- <myTag>
- <my-tag />
- <5‑columns>
- <😍‑happy>
3. How to Create Custom HTML Tags?
We need to follow the below procedure in order to define a custom HTML tag.
- To use the power of these custom tags, we have to first define and add functionalities to them.
- For this purpose, JavaScript comes in handy and helps in creating custom HTML elements.
- We have to convey our message via JavaScript to perform certain functionality whenever the page loads or eliminates a custom HTML element.
- Further, the use of these new HTML5 tags or elements is not different from the regular markup.
- Moreover, the JavaScript object CustomElementRegistry helps in defining a new tag in HTML.
Check the below sample script for how defining custom HTML5 tags is easy and swift.
Example
class newCustomer extends HTMLElement { constructor(){ /* Always call super first */ super(); /* Write functions for these fresh elements. */ } } customElements.define('new-customer', newCustomer); /* Or */ customElements.define('new-customer', class extends HTMLElement {...});
Using Custom Tag
<new-customer></new-customer>
As denoted in the above example, a class defines a new HTML element. Inside the class, there are certain functions, and callbacks to extend its functionality. Let's understand this by a comprehensive example and design a brand new HTML tag.
4. Creating Custom HTML Tag Using JavaScript
Since these advanced formulated HTML tags have proved their usefulness. Now let's create a brand new HTML element using the JavaScript language technique. The first method is to use JavaScript to formulate an HTML tag. Also, we used constructor() and shadow DOM elements to define an element. See the below example to understand the code completely.
Example
class addNote extends HTMLElement { constructor () { /* 1- call constructor at beginning */ super(); /* 2- Shadow DOM elements */ this._wrap = document.createElement ( "div" ); this._text = document.createElement ( "span" ); this._wrap.appendChild ( this._text ); /* 3- Add CSS Styles */ this._styles = document.createElement ( "style" ); this._styles.textContent = ` div { padding: 20px; font-size: 20px; background: #f8f9fa; color: #153966; border-radius: 10px; border-left: 10px solid #153966; box-shadow: 0 0 2px #000; }`; /* 4- Attach CSS styles to Shadow DOM */ this._shadow = this.attachShadow ( { mode: "open" } ); this._shadow.appendChild ( this._styles ); this._shadow.appendChild ( this._wrap ); } /* 5- Add attributes functionality */ static get observedAttributes () { return [ 'text' ]; } attributeChangedCallback ( name, oldVal, newVal ) { /* 6- Add attribute behavior */ if ( name=="text" ) { this._text.innerHTML = newVal; } } /* Callbacks (Optional) */ /* (C1) On Addition to DOM connectedCallback() { console.log( "Connected" ); } /* (C2) On Removal from DOM */ disconnectedCallback() { console.log ( "Disconnected" ); } /* (C3) On Adoption in DOM */ adoptedCallback() { console.log( "Adopted" ); } } /* Register Your Element */ customElements.define ( "add-note", addNote );
In the above example, JavaScript is used to create a new HTML tag. The constructor() {..} holds all the functionality for custom HTML elements.
5. Creating Custom HTML Tags Using Template
Custom HTML5 elements or tags can also be added using the template method. There is a slight difference in JavaScript and template methods which you can easily comprehend in the below instance. Follow the underneath example and understand how to construct a new tag using the HTML template method.
Example
class addRedNote extends HTMLElement { /* Constructor at the beginning */ constructor() { super(); /* Add HTML template into shadow DOM */ this._shadow = this.attachShadow ( { mode: "open" } ); this._shadow.appendChild( document.getElementById ( "add-red-note-temp" ).content ); this._wrap = this._shadow.querySelector ( "div" ); this._text = this._shadow.querySelector ( "span" ); } /* Attributes functionality */ static get observedAttributes () { return [ 'text' ]; } attributeChangedCallback ( name, oldVal, newVal ) { /* Attribute Behaviour */ if ( name=="text" ) { this._text.innerHTML = newVal; } } } /* Register New Element */ customElements.define( "add-red-note", addRedNote );
In the JavaScript code for the template method shown above, it can be observed that the amount of code is lesser compared to the previous JavaScript method. This is because it utilizes the remaining values from a separately provided HTML template. Check the below HTML template and experience in CodeLab Editor to understand it completely.
Example
<template id="add-red-note-temp"> <style> div { padding: 20px; font-size: 20px; background: #fdecea; color: #aa2e25; border-radius: 10px; border-left: 10px solid #aa2e25; box-shadow: 0 0 2px #aa2e25; } </style> <div> <span></span> </div> </template>
6. How to Use Custom HTML5 Tags?
Using HTML5 custom tags is very simple and easy. The element defined in the above example <add-note> is used to display a note on the screen. It is important to note that, an HTML attribute functionality is added to hold the content of the note. See the below example to understand.
Example
<add-note text="This is a note created by JavaScript custom element."></add-note> <add-red-note text="This is a note created by HTML5 custom elements Template Method."></add-red-note>
6.1. Visual Representation of Custom Markup
These HTML elements when utilized in the markup will appear just like the below image. See the tree behavior and added shadow DOM element for the template method.
7. Conclusion
In conclusion, custom HTML tags are a powerful tool for web developers to create expressive and semantic HTML5 markup elements, which definitely increase the productivity. These defined custom elements are more easily understandable by the developers and also by the search engines. Lastly, we discussed both JavaScript and Template methods to define new HTML tags.