標準の HTML 要素が定義されたカスタム内蔵要素のように振舞うよう指定することができます(詳しくは カスタム要素の使用 を参照してください)。
この属性は、指定されたカスタム要素名が現在の文書で正常に定義され、適用されている要素型が拡張されている場合にのみ使用します。
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>
JavaScript: 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' });
表示結果:
→net
表示内容: |
表示内容: |