How to create a custom element without using any framework

Satyendra Kannaujiya
DataDrivenInvestor

--

custom element example which we will build in the tutorial

When we write the User interface using HTML sometime it is not easy to handle complex HTML ( and associated styles and script ) and sometimes you have to rewrite the same code multiple time across the application which can turn page into a mess if you are not careful.

Custom element aim to solve such problem by providing the reusable web component with encapsulate functionality than can be reused wherever you like .

What are custom element —

Using custom element developer can create new HTML tag or can improve the existing HTML tags.Custom element is the way to modernizing HTML , if native HTML does not provide any custom feature you want , You can create custom element that does the same task.

For example if you want to display the details of user you can make a custom element named <user-details></user-details> and can reuse over the application.

DDI Editor’s Pick — The Web Developer Bootcamp

There are some point you should keep in mind while creating custom element

  1. The name of the custom element must contain a dash(-) so <my-element> , <customer-profile> , <journey-details> all are valid custom element name whereas <myComponent> , <fancyButton> are invalid custom element name.This requirement is necessary because HTML parser can distinguish custom element from regular elements.
  2. You can not register the same tag more than once , if you try to do so will throw a DOM Exception.
  3. Custom element can not be self closing because HTML only allow a few elements to be self closing , So always write a closing tag.

The general approach for implementing a web components are —

  1. Create a class or function in which you will specify your web component functionality.
  2. Define your custom element using customElement.define() which take two argument first is tag name and the second arguement is the class in which the functionality is defined and optionally, an options object containing an extends property, which specifies the built-in element your element inherits from if any.
  3. If require attach a shadow DOM to the custom element using Element.attachShadow() method attach all child element and event listener etc to the shadow DOM using regular DOM methods.

4. Use your custom element wherever you like on your page , just like you use regular element.

So the user details element can be define like this —

customElements.define('user-details',UserDetails);

In the above example first argument is the custom tag name and the second is class where functionality are defined.

Custom element are of two types —

  1. Autonomous Custom element — It is standalone and didn’t inherit from standard HTML elements.You use this on page by writing them similar to regular HTML element for example <user-details></user-details>.
  2. Customized build-in element — It inherit from basic HTML elements to create customized version of existing element . They can be use by writing basic HTML element and specify the name of custom element using is attribute. for example <button is='fancy-button'></button> here fancy-button is the custom element which will extend HTMLButtonElement .

Different life cycle hook of an element —

There are different callback inside element class definition which call at different life cycle of the elements —

  1. connectedCallbackIt get called when the element get attached to the documents DOM.
  2. disconnectedCallback — It get invoked each time when the element is remove from the documents DOM.
  3. adoptedCallback — It invoked each time when the custom element move to the new document.
  4. attributeChangedCallback — It invoked each time when any of the attribute get added,removed or changed. The attribute for which we have to notice the changed is specified in the static get observedAttributes method.

Shadow DOM —

It is very important to keep the markup structure, styles and behaviour of custom element hidden and separate from the other code of the page so that different part do not clash.for example there a child element in the custom element whose class name is same as the any element on the page then in this case if we style element on the basis of class name may clash with custom element styles but using shadow DOM we can avoid this.

Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree start with shadow root and then you can attach any element you want in same way as normal DOM.

Theory part is over now let’s create a custom element <user-details></user-details> .

Create two file named index.html and index.js .

class which define the functionality of element.

Let’s understand the code —

Firstly there is a constructor which call the super which is necessary so that correct prototype chain established.

Now observedAttributes() method where we specify the attribute name for which we want to get noticed for attribute changed.

Now get and set for the attribute which simply return and set the attribute value respectively.

Now connectedCallback which called when the element attached to the documents DOM. In which we first create a shadow DOM and then the normal HTML element according to our need.Then we also attach style element to the shadow DOM and then at the end we append all the element to the shadow DOM tree.

Now attributeChangedCallback which takes three parameter attribute name , old value and new value.It invoked when any attribute get changed,removed or added to the element. We check for old value is not equal to new value to prevent overflow of recursion call stack.

At the end we define our custom element using customElements.define() method.

Now using above custom element into our index.html page.

using user details component.

Here we are passing the attribute value like regular HTML element .

you can get full code here — Github link

Thanks for reading 😙.

Editor’s Disclosure: The editors sometimes post affiliate links to useful resources. If you find them useful and make a purchase, we will earn some big bucks. No, I’m not talking about upsizing my fries kind of big. I’m talking about extra pepperoni on a large pizza kind of big. Thank you for your continued support, we will continue to work hard for the p̶e̶p̶p̶e̶r̶o̶n̶i̶ publication.

--

--