I'm trying to understand how the different parts of vanilla web components work together. I have defined a simple custom component and am trying to include a template. I'm doing this since many browser vendors are not supporting html imports and moving towards using es6 modules instead. Here's my web component:
var tmpl = `<template>
<h1>header</h1>
<p>copy</p>
</template>`;
class MyComponent extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
let z = tmpl.cloneNode(true);
this.appendChild(z);
}
}
customElements.define('my-comopnent', MyComponent);
The error I get is Uncaught Type Error: cloneNode is not a function I imagine that has something to do with the way I am defining my template as a string.
My question is this: how do I stamp out my template in a custom component where the template is defined as a javascript string literal? Can I do so without additional dependencies or npm libraries?
Looking at https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
cloneNode
is a method that is on theNode
interface.In your code
tmpl
is not aNode
but astring
.You need to do something like this at the top of your code: