Search code examples
javascriptarraysnodelist

Error in Changing from nodeList to Array in forEach method


I have tried my best to convert my nodeList to an Array using different methods but it still gives this error

Uncaught TypeError: Cannot set property 'display' of undefined at Project.js:68 at Array.forEach () at HTMLSelectElement.filterTodo

I really need a solution or better still, a correction if I'm doing something wrong

function filterTodo(e) {
    const todos = Array.from(todoList.childNodes);
    todos.forEach(function (todo) {
        switch (e.target.value){
            case 'all':
            todo.style.display ='flex';
            break;
        case 'completed':
            if (todo.classList.contains('completed')) {
                todo.style.display ='flex';
            } else {
                todo.style.display ='none';
            }
        }
    })
    
}

Solution

  • todoList.childNodes will also include non-element nodes like text and comment. These non-element nodes do not have a style property, and when you will try to manipulate these by doing todo.style.display, it will rightfully throw this error

    Cannot set property 'display' of undefined

    To get a collection of only the element nodes, use todoList.children instead.

    (Also, there is no issue in the nodeList to an Array conversion. It is fine)