HTML Templates: Difference between revisions
Appearance
No edit summary |
No edit summary |
||
| Line 15: | Line 15: | ||
</code> | </code> | ||
<code> | <code> | ||
const template = document.createElement('template') | |||
const | |||
// | template.innerHTML = ` | ||
<nav> | |||
< | <div> | ||
< | <img src="./assets/logo.png" alt="logo"> | ||
</div> | |||
<ul> | |||
<li><a href="/">Home</a></li> | |||
<li><a href="/about">About</a></li> | |||
<li><a href="/services">Services</a></li> | |||
<li><a href="/contact">Contact</a></li> | |||
</ul> | |||
</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 | |||
class | customElements.define('nav-bar', navBar) | ||
customElements.define(' | |||
</code> | </code> | ||
Revision as of 19:22, 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)
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)