Search code examples
javascripthtmlweb-componentnative-web-componenthtml-templates

Set attributes of node created from template element


The below code fails with console error Uncaught TypeError: node.setAttribute is not a function. How can I change the attributes of nodes created from templates?

const template = document.createElement("template");
template.innerHTML = `<div>hello</div>`;
const node = template.content.cloneNode(true);
document.body.appendChild(node);
node.setAttribute("style", "background-color: green;")

Solution

  • The problem was that the clone doesn't return the div, it returns a document-fragment, using querySelector as per below solves this.

    const template = document.createElement("template");
    template.innerHTML = `<div>supppp</div>`;
    const node = template.content.cloneNode(true);
    node.querySelector("div").setAttribute("style", "background-color: green;");
    document.body.appendChild(node);