Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;")
like image 643
Max888 Avatar asked Dec 14 '25 15:12

Max888


1 Answers

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);

like image 84
Max888 Avatar answered Dec 17 '25 05:12

Max888



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!