everyone.
I am trying to manipulate DOM so whenever the user clicks on the categories, I want their background to change to a pinkish color. I tried to add an eventListener to only the first of those categories (whose class is '.select'), and it worked fine. Then I tried to write code for a for loop that can add eventListeners for all of the options, and it didn't work. Also when I run the code for the case in which only the first option gets impacted, its font color is still not changing. How do I fix these issues? Here are my code segments:
<div class="categorybox">
<ul>
<li class="select"><a href="#">Love</a></li>
<li class="select"><a href="#">Health</a></li>
<li class="select"><a href="#">Beauty</a></li>
<li class="select"><a href="#">Gratitude</a></li>
<li class="select"><a href="#">Sleep</a></li>
<li class="select"><a href="#">Spiritual</a></li>
<li class="select"><a href="#">Happiness</a></li>
<li class="select"><a href="#">Money</a></li>
<li class="select"><a href="#">Blessing</a></li>
</ul>
</div>
const category = document.querySelector(".select");
category.addEventListener("click", (e) => {
e.preventDefault();
category.style.background = "#eb3352";
category.style.opacity = "0.7";
category.style.color = "#fcfafa";
});
In the case above, my font color doesn't change to the color I specified (#fcfafa).
Then I tried running the code below.
const categories = document.querySelectorAll(".select");
for (var i = 0; i < categories.length; i++){
categories[i].addEventListener("click", (e) => {
e.preventDefault();
categories[i].style.background = "#eb3352";
categories[i].style.opacity = "0.7";
categories[i].style.color = "#fcfafa";
}});
In the case above, none of the selected list items changed.