I'm making a simple to-do app where users can add tags to each task.
I store the array of task objects that have tags field. When a user adds a task, it first goes to the local storage, and then the page updates the DOM.
This is a function that updates the DOM:
function createTaskTemplate(task, index) {
return `
<div class="task flex">
<input type="checkbox" class="check-task" onclick="checkTask(${index})"
${task.done ? 'checked' : ''}>
<p class="task-text ${task.done ? 'task-checked' : ''}">${task.name}</p>
// ========= PROBLEM PART ==============
// *Below I create the ul tag that must append a certain amount of li tags*
<ul class="tags"></ul>
// *And here I want to loop over the task's tags, create HTML for them, and put them in the ul created above*
${task.tags.forEach((tag, index) =>
document
.querySelector('.tags')
.appendChild((document.createElement('li').textContent = tag[index]))
)}
// =====================================
</div>`;
}
I get the error Uncaught TypeError: document.querySelector(...) is null. I know that's because this task is not in the DOM at the moment of execution.
How can I solve this? I had an idea of counting the length of the tags array before returning the template and somehow dynamically create the same amount of li tags in the template. But I don't know if it's possible.