[[ウェブコンポーネント]]の一部分に任意のDOMを割り当て可能な要素。 ## 具体例 `owl-card`という[[Custom Elements]]を作成する例。 ![[Pasted image 20210615125418.png]] ### ソースコード `index.html`と`index.js`を作る。`index.js`は[[Custom Elements]]の定義なので本題ではない。 `slot`は要素であり属性でもあるので混同しないように。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="index.js"></script> <title>Document</title> </head> <body> <template id="owl-card-tmpl"> <style> div { border: solid; padding: 7px; width: fit-content; } </style> <div> <h2> <slot name="title">titleのDOMを指定してください</slot> </h2> <p> <slot name="description">descriptionのDOMを指定してください</slot> </p> </div> </template> <div style="display: flex; flex-direction: column; gap: 10px"> <owl-card> <div slot="title">[1] タイトルです</div> <div slot="description">[1] 説明です</div> </owl-card> <owl-card> <div slot="title">descriptionを省略するとデフォルトが使われる</div> </owl-card> <owl-card> <h1 slot="title" style="color: red">div以外でもOK</h1> <div slot="description"> <p>土器の写真でもいける</p> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/bd/Periodo_jomon_medio%2C_vasellame%2C_02.JPG/180px-Periodo_jomon_medio%2C_vasellame%2C_02.JPG" /> </template> </owl-card> </div> </body> </html> ``` ```js customElements.define( "owl-card", class extends HTMLElement { constructor() { super(); let template = document.getElementById("owl-card-tmpl"); let templateContent = template.content; const shadowRoot = this.attachShadow({ mode: "open" }).appendChild( templateContent.cloneNode(true) ); } } ); ``` ### 対応関係イメージ ==⚠️ 理解をしやすくするためのイメージであり、実際のElementはこうならない== [[Custom Elements]] (`owl-card`) を使っている箇所について、コードの中で`slot`属性をもつ要素が置き換わるイメージ。 ```html <template id="owl-card-tmpl"> <style> div { border: solid; padding: 7px; width: fit-content; } </style> <div> <h2> <!-- 次の行は slot="title" 属性を持つElementで置換されるイメージ --> <slot name="title">titleのDOMを指定してください</slot> </h2> <p> <!-- 次の行は slot="description" 属性を持つElementで置換されるイメージ --> <slot name="description">descriptionのDOMを指定してください</slot> </p> </div> </template> ``` たとえば、`owl-card`を使った1つ目の要素の場合。 ```html <owl-card> <div slot="title">[1] タイトルです</div> <div slot="description">[1] 説明です</div> </owl-card> ``` 以下のように置換されるイメージ。 ```html <div> <h2> <div>[1] タイトルです</div> </h2> <p> <div>[1] 説明です</div> </p> </div> ```