<!DOCTYPE html>
<
html
>
<
head
>
<
title
>Web Components</
title
>
</
head
>
<
body
>
<
div
>
<
h1
>HTML Templates</
h1
>
<
template
id
=
"student_template"
>
<
style
>
li {
color: red;
list-style: none;
}
</
style
>
<
li
>
<
span
class
=
"name"
></
span
> —
<
span
class
=
"score"
></
span
>
</
li
>
</
template
>
<
test-element
></
test-element
>
<
ul
id
=
"students"
></
ul
>
</
div
>
<
script
type
=
"text/javascript"
>
class TestElement extends HTMLElement {
constructor() {
super()
const shadowRoot =
this.attachShadow({ mode: "open" });
}
connectedCallback() {
let students = [
{ name: "Emma", score: 94 },
{ name: "Ashton", score: 72 },
{ name: "Hannah", score: 86 },
{ name: "Steve", score: 90 },
{ name: "Amy", score: 75 },
]
students.forEach(student => {
let template =
document.getElementById("student_template");
let templateContent =
template.content.cloneNode(true);
// Append a clone of the template
// content to the shadow root
this.shadowRoot.appendChild(templateContent);
this.shadowRoot.querySelector('.name')
.innerHTML = student.name // Add the name
this.shadowRoot.querySelector('.score')
.innerHTML = student.score // Add the score
// Append the list to the ul students
document.getElementById("students")
.appendChild(this.shadowRoot)
})
}
}
// Register the custom element
customElements.define('test-element', TestElement);
</
script
>
</
body
>
</
html
>