Custom HTML elements

by Imri Paloja

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<!DOCTYPE html>
<html>
<body>

<div class="container">

  <h1>My First Heading</h1>
  <p>My first paragraph.</p>

  <ecms class="file" data-file-fid="001">ecms</ecms>

  <flag-icon country="nl"></flag-icon>


<h1>Reference</h1>

  <ul>
    <li>
    <a href="https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements">HTML Standard#custom-elements</a>
    </li>
    <li><a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements" title="Using custom elements - Web Components | MDN">Using custom elements - Web Components | MDN</a>
</li>
  </ul>

</div>
</body>
</html>

JavaScript

/* let customElementRegistry = window.customElements;
customElementRegistry.define('ecms', ecms);
 */
class FlagIcon extends HTMLElement {
  constructor() {
    super();
    this._countryCode = null;
  }

  static observedAttributes = ["country"];

  attributeChangedCallback(name, oldValue, newValue) {
    // name will always be "country" due to observedAttributes
    this._countryCode = newValue;
    this._updateRendering();
  }
  connectedCallback() {
    this._updateRendering();
  }

  get country() {
    return this._countryCode;
  }
  set country(v) {
    this.setAttribute("country", v);
  }

  _updateRendering() {
    // Left as an exercise for the reader. But, you'll probably want to
    // check this.ownerDocument.defaultView to see if we've been
    // inserted into a document with a browsing context, and avoid
    // doing any work if not.
  }
}

customElements.define("flag-icon", FlagIcon);

/* const flagIcon = new FlagIcon()
flagIcon.country = "jp"
document.body.appendChild(flagIcon) */

const flagIcon = new FlagIcon()
flagIcon.country = "jp"
document.body.appendChild(flagIcon)