--- url: "https://web.dev/articles/custom-elements-v1" titulek: "Custom Elements v1 - Reusable Web Components | Articles | web.dev" h1: "Custom Elements v1 - Reusable Web Components Stay organized with collections Save and categorize content based on your preferences." popis: "Custom elements allow web developers to define new HTML tags, extend existing ones, and create reusable web components." jazyk: "en" kanonicka: "https://web.dev/articles/custom-elements-v1" drobecky: ["Articles", "Custom Elements v1 - Reusable Web Components"] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-14 01:49:42" znaku: 26988 slov: 3857 kodovani: "iso-8859-2" sha256: "2167496a156de977f69f7c9e3057052133667a6e65d6ca9ff4842af1cbf23da1" --- Custom Elements v1 - Reusable Web Components Stay organized with collections Save and categorize content based on your preferences. Custom elements allow web developers to define new HTML tags, extend existing ones, and create reusable web components. Eric Bidelman With [Custom Elements](https://html.spec.whatwg.org/multipage/scripting.html#custom-elements), web developers can **create new HTML tags**, beef-up existing HTML tags, or extend the components other developers have authored. The API is the foundation of [web components](http://webcomponents.org/). It brings a web standards-based way to create reusable components using nothing more than vanilla JS/HTML/CSS. The result is less code, modular code, and more reuse in our apps. Introduction The browser gives us an excellent tool for structuring web applications. It's called HTML. You may have heard of it! It's declarative, portable, well supported, and easy to work with. Great as HTML may be, its vocabulary and extensibility are limited. The [HTML living standard](https://html.spec.whatwg.org/multipage/) has always lacked a way to automatically associate JS behavior with your markup… until now. Custom elements are the answer to modernizing HTML, filling in the missing pieces, and bundling structure with behavior. If HTML doesn't provide the solution to a problem, we can create a custom element that does. **Custom elements teach the browser new tricks while preserving the benefits of HTML**. Defining a new element To define a new HTML element we need the power of JavaScript! The `customElements` global is used for defining a custom element and teaching the browser about a new tag. Call `customElements.define()` with the tag name you want to create and a JavaScript `class` that extends the base `HTMLElement`. **Example** - defining a mobile drawer panel, ``: `class AppDrawer extends HTMLElement {...} window.customElements.define('app-drawer', AppDrawer); // Or use an anonymous class if you don't want a named constructor in current scope. window.customElements.define('app-drawer', class extends HTMLElement {...});` Example usage: `` It's important to remember that using a custom element is no different than using a `
` or any other element. Instances can be declared on the page, created dynamically in JavaScript, event listeners can be attached, etc. Keep reading for more examples. Defining an element's JavaScript API The functionality of a custom element is defined using an ES2015 [`class`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) which extends `HTMLElement`. Extending `HTMLElement` ensures the custom element inherits the entire DOM API and means any properties/methods that you add to the class become part of the element's DOM interface. Essentially, use the class to create a **public JavaScript API** for your tag. **Example** - defining the DOM interface of ``: `class AppDrawer extends HTMLElement { // A getter/setter for an open property. get open() { return this.hasAttribute('open'); } set open(val) { // Reflect the value of the open property as an HTML attribute. if (val) { this.setAttribute('open', ''); } else { this.removeAttribute('open'); } this.toggleDrawer(); } // A getter/setter for a disabled property. get disabled() { return this.hasAttribute('disabled'); } set disabled(val) { // Reflect the value of the disabled property as an HTML attribute. if (val) { this.setAttribute('disabled', ''); } else { this.removeAttribute('disabled'); } } // Can define constructor arguments if you wish. constructor() { // If you define a constructor, always call super() first! // This is specific to CE and required by the spec. super(); // Setup a click listener on itself. this.addEventListener('click', e => { // Don't toggle the drawer if it's disabled. if (this.disabled) { return; } this.toggleDrawer(); }); } toggleDrawer() { // ... } } customElements.define('app-drawer', AppDrawer);` In this example, we're creating a drawer that has an `open` property, `disabled` property, and a `toggleDrawer()` method. It also reflects properties as HTML attributes. A neat feature of custom elements is that **`this` inside a class definition refers to the DOM element itself** i.e. the instance of the class. In our example, `this` refers to ``. This (😉) is how the element can attach a `click` listener to itself! And you're not limited to event listeners. The entire DOM API is available inside element code. Use `this` to access the element's properties, inspect its children (`this.children`), query nodes (`this.querySelectorAll('.items')`), etc. Rules on creating custom elements The name of a custom element **must contain a dash (-)**. So ``, ``, and `` are all valid names, while `` and `` are not. This requirement is so the HTML parser can distinguish custom elements from regular elements. It also ensures forward compatibility when new tags are added to HTML. You can't register the same tag more than once. Attempting to do so will throw a `DOMException`. Once you've told the browser about a new tag, that's it. No take backs. Custom elements cannot be self-closing because HTML only allows [a few elements](https://html.spec.whatwg.org/multipage/syntax.html#void-elements) to be self-closing. Always write a closing tag (``). Custom element reactions A custom element can define special lifecycle hooks for running code during interesting times of its existence. These are called **custom element reactions**. Name Called when `constructor` An instance of the element is created or upgraded. Useful for initializing state, setting up event listeners, or creating a shadow dom. See the [spec](https://html.spec.whatwg.org/multipage/scripting.html#custom-element-conformance) for restrictions on what you can do in the `constructor`. `connectedCallback` Called every time the element is inserted into the DOM. Useful for running setup code, such as fetching resources or rendering. Generally, you should try to delay work until this time. `disconnectedCallback` Called every time the element is removed from the DOM. Useful for running clean up code. `attributeChangedCallback(attrName, oldVal, newVal)` Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial values when an element is created by the parser, or upgraded. **Note:** only attributes listed in the `observedAttributes` property will receive this callback. `adoptedCallback` The custom element has been moved into a new `document` (e.g. someone called `document.adoptNode(el)`). **Reaction callbacks are synchronous**. If someone calls `el.setAttribute()` on your element, the browser will immediately call `attributeChangedCallback()`. Similarly, you'll receive a `disconnectedCallback()` right after your element is removed from the DOM (e.g. the user calls `el.remove()`). **Example:** adding custom element reactions to ``: `class AppDrawer extends HTMLElement { constructor() { super(); // always call super() first in the constructor. // ... } connectedCallback() { // ... } disconnectedCallback() { // ... } attributeChangedCallback(attrName, oldVal, newVal) { // ... } }` Define reactions if/when it make senses. If your element is sufficiently complex and opens a connection to IndexedDB in `connectedCallback()`, do the necessary cleanup work in `disconnectedCallback()`. But be careful! You can't rely on your element being removed from the DOM in all circumstances. For example, `disconnectedCallback()` will never be called if the user closes the tab. Properties and attributes Reflecting properties to attributes It's common for HTML properties to reflect their value back to the DOM as an HTML attribute. For example, when the values of `hidden` or `id` are changed in JS: `div.id = 'my-id'; div.hidden = true;` the values are applied to the live DOM as attributes: `