I have a list like so:
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
And I need to add the class active to each item individually and remove it on the previous item on click.
Something similar to this question Vanilla JS remove class from previous selection however I need to use For loop instead of ForEach due to old browser compatibility.
I've been trying to adapt that answer to my example:
const items = document.querySelectorAll(".item");
for (let i = 0; i < items.length; i++) {
const item = items[i];
item.addEventListener("click", addActiveClass);
for (let i = 0; i < items.length; i++) {
const item = items[i];
item.addEventListener("click", removeClass);
}
}
function removeClass(e) {
e.target.classList.remove("active");
}
function addActiveClass(e) {
e.target.classList.add("active");
}
But it's still not working as expected :(
I assume you need to remove the active class from the rest of the items and then update the correct item. However, I'm not sure that classList
is available in the older browsers you seek to support. You should look into the polyfill for older bowsers.
const items = document.querySelectorAll(".item");
for (let i = 0; i < items.length; i++) {
const item = items[i];
item.addEventListener("click", changeActiveClass);
}
function changeActiveClass(e)
{
for (let i = 0; i < items.length; i++) {
const item = items[i];
item.classList.remove('active');
}
e.target.classList.add('active');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With