Matt
Matt

Reputation: 53

Add class to clicked element, but remove from others

I'm creating some elements using JS, and need to add a class to each item when clicked, but remove it from the non clicked items. I'm sure this is a quick one, but I can't get my head around it.

let data = { 
  label:label, 
  somethingElse:"test", 
  id:id
};

sidebarOptions.push(data);

let ul = document.querySelector(".page-sidebar__options");

sidebarOptions.forEach(sidebarOption => {
  let li = document.createElement('li'),
  button = document.createElement('button'),
  title = document.createElement('span'),
  price = document.createElement('span')  
  ul.appendChild(li);
  li.appendChild(button);
  button.appendChild(title);
  button.appendChild(price);
  title.innerHTML = sidebarOption.label + sidebarOption.id;
  price.innerHTML = '[Price]';
  button.onclick = (event) => {
    button.classList.add('selected');
  };
})

Upvotes: 0

Views: 72

Answers (1)

epascarello
epascarello

Reputation: 207557

So find if you have a selected button and remove the class

const currentlySelected = ul.querySelector('button.selected');
if (currentlySelected) currentlySelected.classList.remove('selected');

Upvotes: 1

Related Questions