<p>Click "Add" button to see what happens:</p>
<button id="btn-add">Add</button>
<button id="btn-rm">Remove</button>
<div id="container">
<!-- Template -->
</div>
<template id="my-temp">
<div>
<span class="name">a name</span>
</div>
<div>
<span class="comment">a comment</span>
</div>
</template>
* {box-sizing: border-box;}
body {
margin: 15px;
color: #222;
font: normal normal normal 1rem/1.6 Nunito Sans, Helvetica, Arial, sans-serif;
}
button {
border: none;
background-color: #0392cf;
color: #fff;
padding: 15px;
}
span {
color: #fff;
padding: 5px 10px;
margin: 2px;
display: inline-block;
}
.name {background-color: #fe4a49;}
.comment {background-color: #222;}
// Check whether browser supports template
if ('content' in document.createElement('template')) {
console.log('Support Template');
}
else {
console.log('Not Support Template');
}
let container = document.querySelector("#container");
let btnAdd = document.querySelector("#btn-add");
let btnRm = document.querySelector("#btn-rm");
let templateFrag = document.querySelector("#my-temp").content;
let data = [
{name: "John", comment: "That is great"},
{name: "Alex", comment: "It's helpful"},
{name: "David", comment: "Thanks a lot"}
];
btnAdd.addEventListener("click", () => {
data.forEach(item => {
let tmpl = templateFrag.cloneNode(true);
tmpl.querySelector('.name').innerText = item.name;
tmpl.querySelector('.comment').innerText = item.comment;
container.appendChild(tmpl);
});
});
btnRm.addEventListener("click", () => {
while(container.firstChild) {
delete container.removeChild(container.firstChild);
}
});
/* Ref
https://davidwalsh.name/convert-html-stings-dom-nodes
https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
*/
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.