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;")
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With