I'm a beginner building a todo list app in vanilla JS. Im trying to create function that filters through the todo items and displays the items the are either completed , in-completed or All task but im running into the error
task.style is undefined"
const filterTask = document.querySelector('.filter-options'); //select tag in HTML which allows user to select whether they want to display the completed or in-completed task
const todoUl = document.querySelector('.todo-ul'); //the ul under which the tasks become childNodes
filterTask.addEventListener('click', filterTodo)
function filterTodo(e) {
const tasks = todoUl.childNodes;
tasks.forEach((task) => {
switch (e.target.value) {
case "all-task":
task.style.display = "flex";
break;
case "completed-task":
if (task.classList.contains('completed-task')) {
task.style.display = "flex";
} else {
task.style.display = "none";
}
}
})
<select class="filter-options">
<option value="all-task">All Task</option>
<option value="completed-task">Completed Task</option>
<option value="uncompleted-task">Uncompleted Task</option>
</select>
childNodes returns NodeList which is a collection of nodes. The issue here that this collection contains not only Elements but also Text nodes. Text node doesn't have style property, therefor it's undefined.
Instead using childNodes, use children which returns only Elements.
The difference between childNodes and children.
const ul = document.querySelector('ul');
const childNodes = [...ul.childNodes].map(node => node.nodeName);
const children = [...ul.children].map(node => node.nodeName);
console.log(`childNodes nodes [${childNodes.join()}]`);
console.log(`children nodes [${children.join()}]`);
<ul>
<li>foo</li>
</ul>