How can I edit the style of a template-clone object? / object that will be created in the future?

document.addEventListener("DOMContentLoaded", ()=>{
    let template = document.querySelector(".template");
    let button = document.querySelector(".button");
    let screen = document.querySelector(".screen");
    button.addEventListener("click", ()=>{
    let template_clone = template.content.cloneNode(true);
    template_clone.style.background = "red";
    screen.appendChild(template_clone)
})})

I need to add an object to the screen that is a template clone and edit its style

<body>
    <button class="send">send</button>
    <div class="screen">
        <template class="template">
        <div class="box1"></div>
    </template>
    </div>       
</body>

if I try to edit the template_clone.style style it results in an error

undefined is not an object (evaluating 'template_clone.style.background = "red"')

The error you’re encountering happens because template.content itself doesn’t have a style property. It’s a DocumentFragment, which is a lightweight container for nodes but doesn’t have its own styles. Here’s how you can fix it:

1. Access the first child element (.box1) and modify its style:

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  let template = document.querySelector(".template");
  let button = document.querySelector(".button");
  let screen = document.querySelector(".screen");

  button.addEventListener("click", () => {
    let template_clone = template.content.cloneNode(true);
    let box1 = template_clone.querySelector(".box1"); // Get the first child element
    box1.style.background = "red"; // Modify style of the box1 element
    screen.appendChild(template_clone);
  });
});

Explanation:

  • We use querySelector on the template_clone to get the first child element, which is the .box1 div in this case.
  • We then access the .style property of the retrieved element and set its background color to “red”.

2. Modify the entire clone’s style (less recommended):

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  let template = document.querySelector(".template");
  let button = document.querySelector(".button");
  let screen = document.querySelector(".screen");

  button.addEventListener("click", () => {
    let template_clone = template.content.cloneNode(true);
    template_clone.style.background = "red"; // Modify style of the entire clone (less recommended)
    screen.appendChild(template_clone);
  });
});