Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a class to one and only one element from an HTML list on click

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 :(

like image 907
Nesta Avatar asked Jun 24 '20 15:06

Nesta


1 Answers

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');
}
like image 160
Matt Ellen Avatar answered Nov 15 '22 19:11

Matt Ellen