const navLinks = document.querySelectorAll(".nav-link");
navLinks.forEach((link) => {
link.addEventListener("click", (e) => {
console.log(e.target.classList);
return e.target.classList.toggle("active");
});
});
When I log out the classlist I get a list of all elements with the navLink class, not the clicked one. I have a feeling it's the for each function I am using. How do I get the correct classist as in for the clicked link? , right now when I log out I get classes in all the navlink elements
Use stopPropagation to prevent further propagation of events
classList is ArrayLike object, not actually an array. But it can be converted to Array.
const navLinks = document.querySelectorAll(".nav-link");
navLinks.forEach((link) => {
link.addEventListener("click", (e) => {
e.stopPropagation(); // prevents further propagation of the current event in the capturing and bubbling phases
console.log('Array: ', Array.from(e.target.classList));
console.log('ArrayLike: ', e.target.classList);
return e.target.classList.toggle("active");
});
});
.nav-link {
width: 150px;
height: 50px;
border: 1px solid gray;
}
<div class="nav-link 1-item"></div>
<div class="nav-link 2-item"></div>
<div class="nav-link 3-item"></div>
<div class="nav-link 4-item"></div>