HTML Templates: Difference between revisions
Appearance
No edit summary |
No edit summary |
||
| Line 15: | Line 15: | ||
</code> | </code> | ||
<code>< | <code><script>> | ||
const template = document.createElement('template') | const template = document.createElement('template') | ||
| Line 41: | Line 41: | ||
// define a custom element called 'nav-bar' using the navBar class | // define a custom element called 'nav-bar' using the navBar class | ||
customElements.define('nav-bar', navBar) | customElements.define('nav-bar', navBar) | ||
</code></ | </code></script> | ||
Revision as of 19:25, 7 January 2026
//creating template
<template>
<section>
HTML Templates
everything in a template tag is not displayed on the browser.
</section>
</template>
//using template
const template = document.querySelector('template')
const clone = template.content.cloneNode(true)
document.querySelector('main').appendChild(template)
<script>>
const template = document.createElement('template')
template.innerHTML = `
<nav>
<img src="./assets/logo.png" alt="logo">
- <a href="/">Home</a>
- <a href="/about">About</a>
- <a href="/services">Services</a>
- <a href="/contact">Contact</a>
</nav>
`
// create a navBar class, and clone the content of the template into it
class navBar extends HTMLElement {
constructor() {
super()
this.attachShadow({ mode: 'open' })
this.shadowRoot.appendChild(template.content.cloneNode(true))
}
}
// define a custom element called 'nav-bar' using the navBar class
customElements.define('nav-bar', navBar)
</script>