Alexandr Belov
Alexandr Belov

Reputation: 1834

Remove one of multiple classes if it exists Javascript

I need to check and remove a specific class of an element. I need it to be done using Javascript only, what I managed to find were mainly JQuery or non-working variants to me.

Here's my code:

 <ul>
   <li class = "tab"><a href="#">One</a></li>
   <li class = "tab"><a href="#">Two</a></li>
   <li class = "tab active"><a href="#">Three</a></li>
   <li class = "tab"><a href="#">Four</a></li>
 </ul>


 var NumThree = document.querySelector("li.tab active")

 function removeActiveClass(){
     if(NumThree !== null) {
         NumThree.classList.remove("active")
     }
 }

and FIDDLE

My code doesn't remove the class. So I am asking for 100% Javascript help!

Upvotes: 0

Views: 793

Answers (3)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

Couple of Typos, Working Fiddle . The problem was in the way you were using the selectors, document.querySelector("li.tab active") will look for a element names active inside your li with the class tab (the space is used to search for a child element). what you actually wanted is a li with both the class tab and active so it should be document.querySelector("li.tab.active")

var NumThree = document.querySelector("li.tab.active")

function removeActiveClass(){    
    if(NumThree !== null) {
      NumThree.classList.remove("active");
    }
}

removeActiveClass();

Upvotes: 3

Andy
Andy

Reputation: 63524

As the other answers pretty much have this covered, you might think about how you could refactor the code so that the function is reusable.

Here, pass in the element and class as parameters to a more general function:

function removeClass(el, c) {
  if (el) el.classList.remove(c);
}

var NumThree = document.querySelector('li.tab.active')
removeClass(NumThree, 'active');

Upvotes: 1

Lionel T
Lionel T

Reputation: 1597

You need to correct selector into document.querySelector("li.tab.active") or just into document.querySelector(".active")and fire the function as removeActiveClass(). Like here.

Upvotes: 6

Related Questions