Tarea: al hacer clic en el círculo, debería volverse rojo. Presionando de nuevo debería volver a su estado original. Parece que todo es correcto, indicado, pero el script no funciona, ayuda. Error de consola - "mensaje": "Error de tipo no detectado: favorito.addEventListener no es una función" - ¿Por qué?
const favorite = document.querySelectorAll('.clothes__item-favorite'); favorite.addEventListener('click', function() { favorite.classList.toggle("favorite--active"); }); body { background-color: #000; } .clothes__item-favorite { display: block; position: absolute; background-color: #fff; width: 2.3rem; height: 2.3rem; border-radius: 100%; left: 1.25rem; top: 1.25rem; font-size: 0; transition: 0.3s; cursor: pointer; } .clothes__item-favorite:hover { background-color: #fc7a7a; } .favorite--active { background-color: #fc7a7a; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <i class="clothes__item-favorite">Добавить в избранное</i> </body> </html>Intenta hacer esto:
const favorite = document.querySelectorAll('.clothes__item-favorite'); for (element of favorite) { element.addEventListener('click', function() { element.classList.toggle("favorite--active"); }); }document.querySelectorAll devuelve una iteración de todos los elementos que coinciden con el selector. Tienes que iterar sobre cada elemento.
Es porque está usando .querySelectorAll() . Use .querySelector() en su lugar porque solo está seleccionando un solo elemento. querySelectorAll selecciona una colección. El siguiente código debería funcionar.
//changed querySelectorAll to querySelector const favorite = document.querySelector('.clothes__item-favorite'); favorite.addEventListener('click', function() { favorite.classList.toggle("favorite--active"); }); body { background-color: #000; } .clothes__item-favorite { display: block; position: absolute; background-color: #fff; width: 2.3rem; height: 2.3rem; border-radius: 100%; left: 1.25rem; top: 1.25rem; font-size: 0; transition: 0.3s; cursor: pointer; } .clothes__item-favorite:hover { background-color: #fc7a7a; } .favorite--active { background-color: #fc7a7a; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <i class="clothes__item-favorite">Добавить в избранное</i> </body> </html>