2

I m building a menu bar which has current class which is highlighted when user clicks.

how do i make it so when someone clicks on li it removes from previous li and put it on new li which is clicked on ??

here is my code

li.forEach(li => {
  li.addEventListener('click', () => {
      li.classList.add("selected");
      li.style.background = '';
      li.style.paddingTop = '';
  });
});

3 Answers 3

1

You could do something like this

li.forEach(li => {
  li.addEventListener('click', () => {
      removeClass();
      li.classList.add("selected");
      li.style.background = '';
      li.style.paddingTop = '';
  });
});

function removeClass () {
  li.forEach(li => {
    li.classList.remove("selected");
  })
}
0
0

how about this

items.forEach(li => {
  li.addEventListener('click', () => {
      items.forEach(li => li.classList.remove("selected"));
      li.classList.add("selected");
      li.style.background = '';
      li.style.paddingTop = '';
  });
});
1
  • cheers matt. but this not seems to be working. i guess you cant loop through again in a loop same thing
    – ummzi
    Commented Jun 8, 2018 at 18:33
0

One simple approach is the following:

li.forEach(li => {
  li.addEventListener('click', () => {

      // find the parent-node of the current <li> element:
      li.parentNode

        // use Element.querySelector() to find the current
        // <li> element with the 'selected' class:
        .querySelector('li.selected')

        // use classList.remove() to remove that class-name:
        .classList.remove('selected');

      // as before:
      li.classList.add("selected");

      // why is the following necessary? It *seems* to be
      // undoing something that shouldn't be necessary:
      li.style.background = '';
      li.style.paddingTop = '';
  });
});

References:

Not the answer you're looking for? Browse other questions tagged or ask your own question.