Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
classList.toggle() behaves strange

I am trying to learn Javascript by creating this very simple todo app. I can type some value in input. When pressed enter or submit button, the value from input tag is added to the ul as a list. Then a class 'list-item' is added to that li tag.

My issue is: I want to cross any individual list when clicked. I have used following code for that. I have the 'cross' style in my CSS, but the problem is that my code does not cross every individual list. It crosses every-other one. I tried forEach as well and the result is same.

const listItems = document.querySelectorAll('list-item');

for (let i=0; i<listItems.length; i++) {
    
    listItems[i].addEventListener('click', function() {
        console.log(listItems[i])
        listItems[i].classList.toggle('cross');
    })
}

my whole javascript :

const input = document.getElementById('main-input')
const submit = document.getElementById('submit')
const ul = document.getElementById('to_dos');
const del = document.getElementById('del')

//clicking submit button
submit.addEventListener('click', function() {
    addList()
})

//pressing enter key
input.addEventListener("keypress", function(event) {
    if(event.keyCode === 13) {
        event.preventDefault()
        addList()
        
    }
})

//add new todo in the list from input
const addList = () => {
    const newToDo = document.createElement('LI')
    newToDo.classList.add('list-item')
    newToDo.appendChild(document.createTextNode(input.value))
        
        
    ul.appendChild(newToDo)
    input.value = "" 
    
    //cross the completed tasks
    const listItems = document.querySelectorAll('li.list-item');
    
    for (let i=0; i<listItems.length; i++) {
        
        listItems[i].addEventListener('click', function() {
            console.log(listItems[i])
            listItems[i].classList.toggle('cross');
        })
    }


    //delete button
    del.addEventListener('click', function() {
        const completedItems = document.querySelectorAll('.cross');
        completedItems.forEach(
            completedItem => {
                completedItem.classList.add('hide')
            }
        )
    })
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In your codepen, you are assigning the click listener incorrectly. Rather than attaching a listener to each added item individually, you are loop through ALL the items EACH time a new one is added - and when you compound event listeners like that it can have undesireable results.

In your addList function, rather than looping through all inputs with this:

        //cross the completed tasks
        const listItems = document.querySelectorAll('li');
        
        listItems.forEach(listItem => listItem.addEventListener('click', e => {
            e.target.classList.toggle('cross');
        }))

Just attach the listener to the new one added:

        newToDo.addEventListener('click', e => {
            e.target.classList.toggle('cross');
        })

Example: https://codepen.io/chayashital/pen/jOGaWgJ#_=_

about 4 years ago · Juan Pablo Isaza Denunciar

0

you just forget to add dot (.) at the beggining of the querySelectorAll method. in your case you told querySelectorAll method to find all list-item tag so that dot will change the meaning to find all list-item class. and querySelectorAll will return HTMLCollection not Array so the forEach method will not work you should return it to a Array using Array() function or the following way.

[...document.querySelectorAll('.list-item')]
.forEach(function(element){
    element.addEventListener("click", function(){
        element.classList.toggle("cross")
})
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda