๐Ÿ”ธcustom element

browser โŸฉ web components โŸฉ implement โŸฉ custom elements

// define new custom element
customElements.define(
  'web-component',                    // โญ๏ธ HTML tag name, must have "-"โ—๏ธ 
  class extends HTMLElement { ... }   // โญ๏ธ must extend `HTMLElement`โ—๏ธ 
);

Valid Custom Element Name

  • ้–‹้ ญ๏ผš[a-z] โญ๏ธ

  • ๆŽฅ่‘—๏ผš[0-9], [a-z], "-", ".", "_" (optional)

  • ไธญ้–“ไธ€ๅฎš่ฆๆœ‰๏ผš"-" โญ๏ธ

  • ๆŽฅ่‘—๏ผš[0-9], [a-z], "-", ".", "_" (optional)

<vstack-> ๆˆ– <i-vstack> โ“(้€™ๅ…ฉๅ€‹้ƒฝๆ˜ฏๅˆๆณ•็š„ๅๅญ—)

PotentialCustomElementName ::= 
    [a-z] (PCENChar)* '-' (PCENChar)*
    
PCENChar ::=
    "-" | "." | [0-9] | "_" | [a-z] | #xB7 | 
    [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x37D] | [#x37F-#x1FFF] | 
    [#x200C-#x200D] | [#x203F-#x2040] | [#x2070-#x218F] | 
    [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | 
    [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]

Register New Tag Name

We can create our tags by using the CustomElementRegistry object (window.customElements).

// โญ๏ธ custom tag <my-component>
// โญ๏ธ custom element names must contain a "hyphen".
customElements.define('my-component', MyComponent);

Supporting Class

To create a custom element, we need to tell the browser several details about it: how to show it, what to do when the element is added or removed to page, etc.

class MyComponent extends HTMLElement {

  constructor() {
    super();
    // ...
  }

  // triggered when added to the document
  connectedCallback() {}

  // triggered when removed from the document
  disconnectedCallback() {}

  // attribute names to monitor for changes
  static get observedAttributes() {
    return [ /* ... */ ];
  }

  // triggered when one of attributes listed above is modified.
  // doesnโ€™t trigger for unlisted attributes (for performance reasons).
  attributeChangedCallback(name, oldValue, newValue) {}

  // called when moved to a new document
  // happens in document.adoptNode, very rarely used
  adoptedCallback() {}

  // other methods and properties ...
}

Last updated

Was this helpful?