Created
November 29, 2017 14:36
-
-
Save prof3ssorSt3v3/d5d92044d037ab4513e3fe5e5e9c8ffb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>HTML Templates</title> | |
<meta name="viewport" content="width=device-width"> | |
<style> | |
.temp{ | |
background-color: cornflowerblue; | |
color: #fff; | |
} | |
.box{ | |
border: 1px solid #bbb; | |
padding: 1rem; | |
max-width: 400px; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Using HTML5 Templates</h1> | |
<p>Paragraph above the template.</p> | |
<template id="myTemplate"> | |
<div class="box"> | |
<h2 class="temp">A Sub Heading</h2> | |
<p>Some template created text.</p> | |
</div> | |
</template> | |
<p>Paragraph below the template.</p> | |
<script> | |
const supportsTemplate = function() { | |
//create a template element and make sure it has a 'content' property | |
return 'content' in document.createElement('template'); | |
} | |
document.addEventListener('DOMContentLoaded', ()=> { | |
if (supportsTemplate()) { | |
//We can use the template element in our HTML | |
console.log('Templates are supported.'); | |
let temp = document.getElementById('myTemplate'); | |
let content = temp.content; | |
console.log(content); | |
document.body.appendChild(content.cloneNode(true)); | |
document.body.appendChild(content.cloneNode(true)); | |
document.body.appendChild(content.cloneNode(true)); | |
document.body.appendChild(content.cloneNode(true)); | |
document.body.appendChild(content.cloneNode(true)); | |
document.body.appendChild(content.cloneNode(true)); | |
document.body.appendChild(content.cloneNode(true)); | |
} else { | |
//Use another method, like manually building the elements. | |
console.log('The else is running'); | |
let df = document.createDocumentFragment(); | |
let div = document.createElement('div'); | |
let h2 = document.createElement('h2'); | |
let p = document.createElement('p'); | |
h2.textContent = 'A Sub Heading'; | |
p.textContent = 'Some dynamically created text.'; | |
div.className = 'box'; | |
h2.className = 'temp'; | |
df.appendChild(div); | |
div.appendChild(h2); | |
div.appendChild(p); | |
document.body.appendChild(df); | |
} | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment