0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

カスタム要素を使ってみる(カスタマイズされた組み込み要素)(Web Components)

Posted at

概要

紹介ページのSampleに従って、カスタム要素を使ってみる。

今回は、カウントした文字数を表示するカスタマイズされた組み込み要素。(is属性を用いる)

内容

環境

macOS Catalina
Firefox 86.0

全体像

wordcount.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Simple word count web component</title>
  </head>
  <body>
    <h1>Word count rating widget</h1>
    <article contenteditable="">
      <h2>Sample heading</h2>

      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
      <p>Pellentesque ornare tellus sit amet massa tincidunt congue.</p>
      <p is="word-count"></p>
    </article>

    <script src="main.js"></script>
  </body>
</html>
main.js
// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    super();

    function countWords(node){
      const text = node.innerText || node.textContent;
      return text.split(/\s+/g).length;
    }

    const wcParent = this.parentNode;
    const count = `Words: ${countWords(wcParent)}`;
    const text = document.createElement('span');
    text.textContent = count;

    // Create a shadow root
    const shadow = this.attachShadow({mode: 'open'});
    shadow.appendChild(text);

    // Update count when element content changes
    setInterval(function() {
      const count = `Words: ${countWords(wcParent)}`;
      text.textContent = count;
    }, 200);
  }
}

// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });

(少しソースは個人的に見やすく変更した。)

スクリーンショット 2021-03-08 18.15.56.png

前提として2種類

前提としてカスタム要素には、2種類ある。

  • 自律カスタム要素:標準のHTML要素を継承しない。例:<popup-info>
  • カスタマイズされた組み込み要素 :標準のHTML要素を継承する。例:<p is="word-count">(is属性を使う)

カスタム要素を記載する

      <p is="word-count"></p>

カスタム要素を定義する

CustomElementRegistry.define()を用いて、カスタム要素を登録する。

customElements.define('word-count', WordCount, { extends: 'p' });
  • 'word-count': カスタム要素の名前。1つ以上の-が必要。
  • WordCount: カスタム要素の振る舞いを定めるclass。
  • {extends: 'p'}: built-in要素で性質を引き継ぐもの。(なくても良い)

カスタム要素のクラスを定義する。(WordCount)

HTMLParagraphElementを拡張して、WordCountを定義する。

class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Element functionality written in here
    ...
  }
}

蛇足

これだけならカスタム要素を使うまでないが、

  • ドキュメント接続要素にカスタム要素が追加されるたびに実行
  • カスタム要素に属性が追加、削除、変更されるたびに実行

などのこともできるとのこと。

参考にさせていただいた本・頁

感想

たまに見かけたis属性の使われ方の意味がわかって良かった。

今後

自律カスタム要素の方も確認したい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?