How to create a custom element(tag) in HTML5?

·

1 min read

Until HTML5 , reusing a piece of html code was not straightforward. Thanks to HTML5 , web components came into picture. Now you can create your own custom components and include them in your HTML code using custom tags. And you can reuse them anywhere else in your application by declaring the custom tags just like you declare your standard HTML tags.

You do this by extending HTMLElement class in Javascript.

Here is the algorithm:

STEP1: Create a custom element class which extends HTMLElement class , using Javascript .

STEP2: Inside this class create a constructor and call super() keyword . This calls the constructor of HTMLElement class which is mandatory.

STEP3: Create a shadow DOM and attach all your html elements to it.

STEP4: While you append custom elements to the shadow root , you can also create custom attributes for the new element , retrieve their values and assign it to your html elements.

STEP5: Once your custom element class is ready , define the custom tag outside the class .

Here is a quick demo of it:

fullstackdeveloper.guru/2020/11/06/how-to-c..