Vadim Vedenin
Vadim Vedenin

Reputation: 1

How to correctly clone content of <template> in JS

I am creating simple “to do list” by Java Script. I have template for tasks, which content I would like to clone, and then I am trying to insert task’s text inside this content.

<template id="li-temp">
    <li class="todo-item__undone"></li>
    <button class="delete-item-button delete-item-button-not-displayed">&#10008;</button>
</template>

A method, which try to clone template's content and insert task's content:

createTaskHtml(content, status, id){
    let template = document.getElementById("li-temp").content.cloneNode(true);
    let li = template.firstChild;
    let li_test = document.createElement("li")
    li.id = id;
    li.innerText = content;
    let deleteButton = template.lastChild;
    if (status === "done"){
        li.classList.add("todo-item__done");
        deleteButton.classList.remove("delete-item-button-not-displayed");
        this.setListener(deleteButton);
    }
    return li;
}

I used "content" to get template's content, then I used method "cloneNode(true)" for deep cloning. I am expecting to get node with two children (li and button), so I am truing to get object li as firstChild. But then I am getting an error becouse object li doesn't have attribute "id" and "innerText".

I debuged this code and was surprised to find that WebStorm identified this node as text node. So I assume that I am somehow copying the content of the template incorrectly, but, of course, I admit that the error may be in something else

Upvotes: 0

Views: 566

Answers (2)

somerandome23423
somerandome23423

Reputation: 1

  function createCards(data) {
      const template = document.getElementById('card-template');

      data.forEach(item => {
        const clone = document.importNode(template.content, true);

        // Customize the cloned content
        clone.querySelector('#card-title').textContent = item.title;
        clone.querySelector('#card-content').textContent = item.content;

        // Insert the cloned content into the DOM
        document.getElementById('card-container').appendChild(clone);
      });
    }

    // Create cards with the provided data
    createCards(cardData);

Upvotes: 0

user15392855
user15392855

Reputation:

Return template variable not li

Upvotes: 1

Related Questions