Jump to content

HTML Templates: Difference between revisions

From Drywall Wiki
No edit summary
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
<code>


<!--
//creating template
//creating template
<template>
<template>
Line 14: Line 14:
document.querySelector('main').appendChild(template)
document.querySelector('main').appendChild(template)


</code>
-->
<h2> Shadow DOM</h2>
<!-- const template = document.createElement('template')
<code>
 
// create a div element
template.innerHTML = `
const htmlSection = document.createElement('div')
<nav>
// create HTML using template literals
    <div>
const content = `
        <img src="./assets/logo.png" alt="logo">
<h3>This is a heading</h3>
    </div>
<p>this content is meant to be added to the shadow DOM</p>
    <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>
`
`
htmlSection.innerHTML = content
// create a navBar class, and clone the content of the template into it
// select the element with a class called root
class navBar extends HTMLElement {
const root = document.querySelector('.root')
    constructor() {
// attach a shadow DOM to the selected element
        super()
root.attachShadow({ mode: 'open' })
        this.attachShadow({ mode: 'open' })
// append the html element to the shadow DOM
        this.shadowRoot.appendChild(template.content.cloneNode(true))
root.shadowRoot.appendChild(htmlSection)
    }
</code>
}
<h2>create custom element</h2>
// define a custom element called 'nav-bar' using the navBar class
class anyName extends HTMLElement {}
customElements.define('nav-bar', navBar)
customElements.define('custom-element', anyName)
-->
//now use custom component
<custom-element>Some text here</custom-element>
</code>

Latest revision as of 19:28, 7 January 2026