概要
紹介ページの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' });
(少しソースは個人的に見やすく変更した。)
![]() |
---|
前提として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
...
}
}
蛇足
これだけならカスタム要素を使うまでないが、
- ドキュメント接続要素にカスタム要素が追加されるたびに実行
- カスタム要素に属性が追加、削除、変更されるたびに実行
などのこともできるとのこと。
参考にさせていただいた本・頁
- https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements
- https://developer.mozilla.org/ja/docs/Web/Web_Components/Using_custom_elements
感想
たまに見かけたis
属性の使われ方の意味がわかって良かった。
今後
自律カスタム要素の方も確認したい。