Back to Lit

01

packages/lit-dev-content/site/tutorials/content/wc-to-lit/01.md

latest2.1 KB
Original Source

Custom Elements

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

  • ES Modules
  • Custom Elements
  • Shadow DOM
  • HTML Templates

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

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 <code>rating-element.<ts-js></ts-js></code> file and define a custom element class:

rating-element.<ts-js></ts-js>

{% switchable-sample %}

ts
class RatingElement extends HTMLElement {}

customElements.define('rating-element', RatingElement);
js
class RatingElement extends HTMLElement {}

customElements.define('rating-element', RatingElement);

{% endswitchable-sample %}

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.

{% aside "warn" %}

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.

{% endaside %}

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

index.html

html
<body>
 <rating-element></rating-element>
</body>

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:

text
document.querySelector('rating-element').constructor

Which should output:

js
class RatingElement extends HTMLElement {}