Task - When you click on the circle, it should turn red. Pressing again should return to its original state. It seems that everything is correct, indicated, but the script does not work, help. Console error - "message": "Uncaught TypeError: favorite.addEventListener is not a function" - why is that?
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>
Try doing this:
const favorite = document.querySelectorAll('.clothes__item-favorite');
for (element of favorite) {
element.addEventListener('click', function() {
element.classList.toggle("favorite--active");
});
}
document.querySelectorAll returns an iterable of all elements matching the selector. You have to iterate over every single element.
It is because you are using .querySelectorAll(). Use .querySelector() instead because you are only selecting a single element. querySelectorAll selects a collection. Below code should work.
//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>