Custom Elements

Permalink to "Custom Elements"

Web components are a collection of 4 native web APIs. They are:

You've likely already used the ES modules specification, which allows you to create JavaScript modules with imports and exports that are loaded into the page with <script type=”module”>.

Defining a Custom Element

Permalink to "Defining a Custom Element"

The custom elements specification lets users define their own HTML elements using JavaScript. The names must contain a hyphen (-) to differentiate them from native browser elements. Clear the rating-element. file and define a custom element class:

rating-element.

Permalink to "rating-element."

You define a custom element by associating an element class with a tag name. The class must extend HTMLElement, and the tag name must must contain a hyphen (-) to differentiate it from a native browser elements.

Custom Element names are global.

Since customElements.define has a global scope, you cannot currently call it more than once for the same tag name even if the same class definition is given.

Place a <rating-element> in the document body and see what renders.

index.html

Permalink to "index.html"

Looking at the output, you'll see that nothing has rendered. This is file; you haven't told the browser how to render the element yet.

You can confirm that the custom element definition has succeeded by right-clicking on the result preview window, selecting "inspect" or "inspect element", and checking the constructor of the <rating-element> by calling the following expression in the console:

Which should output: