Introduction to Custom Elements in HTML5

Custom elements are a new way to package things for users. Once you make a custom element you can use it anywhere you want and as many times as you wish. Making a custom element is pretty simple.

The document object now has a new method called register which can register your custom elements in your document for use throughout the page.

document.register('tag-name', {
  prototype: proto
});

The two prerequisites are that the tag name must have a dash and proto must inherit from HTMLElement.
Let’s take a simple example:

var tmpl = document.querySelector("#my-template");
var widgetPrototype = Object.create(HTMLElement.prototype);
widgetPrototype.createdCallback = function () {
  var root = this.createShadowRoot();
  root.appendChild(tmpl.content.cloneNode(true));
};
var widget = document.register('my-widget', { prototype: widgetPrototype });

Here, consider I have a template somewhere with the id of my-template. I create a prototype widgetPrototype which inherits from HTMLElement. createdCallback is a special kind of callback which is executed when the prototype is created. In the callback function, I create a shadow root and append it to my element (Want to know how to create a shadow root, visit this). Then I register my tag by using document.register and give it a tag name of my-widget and assign its prototype to the one I created.

Now you’re ready to use your custom element. There are three ways to do that:

  1. Either you can write <my-widget></my-widget> in the HTML part.
  2. You can create the element from JavaScript like document.createElement('my-widget');
  3. Or you can declare it using a new constructor like new widget();

To know more about Shadow DOM, Custom Elements and HTML Templates, watch this video.

Advertisements

Your Thoughts -

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s