1

I am trying to add a class .active if the target element does not have that class, and if another element has that class I want to remove that class so only that class I clicked on has that element. I am trying to do this with this code -

document.addEventListener('click',function(e){
    document.querySelector('.active').classList.remove('.active');
    if(!e.target.classList.contains('active') && e.target.classList.contains('day')){
        e.target.classList.add('active');
    }
 });

I expect that whatever has the .active class to be removed when I click on another element, but instead when I click on another element the active class remains on the element that already had the active class and it is added onto the target that I clicked on. I have no errors in my console.

2
  • document.querySelector('.active') will only select the first element with that class. You might want to check the API documentation when having problems with it: developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
    – connexo
    Commented Nov 10, 2018 at 12:51
  • I only want the first element with that class to be selected because whatever the first element is, is what I last clicked on. I also tried document.getElementsByClassName('active')[0] but got the same results. I'm not sure what I should use to select the last element that I clicked on or whatever has the .active class.
    – icewizard
    Commented Nov 10, 2018 at 12:52

1 Answer 1

3

It has to be

document.querySelector('.active').classList.remove('active')

not

document.querySelector('.active').classList.remove('.active')

As you already told the browser it's about CSS classes (classList), you no longer prefix the class you specify with a ..

0

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