How to add and remove classes with Javascript?

Asked

Viewed 2,823 times

3

I want to know how to add and remove a class in HTML elements with Javascript.

<div>
 <ul>
  <li class="Active">1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
 </ul>
</div>

3 answers

4

There is the API classList, which is basically a DOMTokenList containing all classes of a given element.

The estate classList can be accessed in objects that implement Element.

First you get the element:

const element = document.querySelector('#my-element');

And then you can...

  1. Add a new class to the list:

    element.classList.add('new-class');
    
  2. Remove a class from the list:

    element.classList.remove('new-class');
    
  3. Trade one class for another:

    element.classList.replace('old-class', 'new-class');
    
  4. Do the toggle of a class. That is, add the class if it does not exist and otherwise remove:

    element.classList.toggle('is-active');
    

Like property classList is nothing more than a DOMTokenList, exist several other methods that may help in other situations.


The advantage of the API classList is that you don’t need to modify all the class string directly (what is needed with the API className). It also has several methods that make the job simpler. Some of them have been demonstrated above.

About the support of this API, see table. Although it is newer than the API className, support for modern browsers is already relatively good.

1


To remove the class, set the element class to empty:

// Pega o primeiro li e remove a classe
document.getElementsByName("li")[0].className = "";

If you want to keep some class, restore the class:

document.getElementsByName("li")[0].className = "";
document.getElementsByName("li")[0].className = "classe_que_fica";

0

With pure Javascript, I thought of something like:

// Selecionando elemento no DOM
elemento = document.getElementsByName('li')[0];

// Limpando o atributo class
elemento.className = '';

// Se você quisesse remover uma classe específica, digamos que houvesse
// mais de uma classe no seu elemento (class="Active estilo1"):
element.className = element.className.replace('estilo1','');

// a linha de comando anterior, resultaria em class="Active ", o que 
// significa que você retirou o texto correspondente da classe "estilo1".
// Para remover o espaço extra, pode utilizar .trim() :
element.className = element.className.trim();
  • Please provide additional details in your reply. As it is currently written, it is difficult to understand your solution.

  • Please add more details to expand your response, such as a working code or documentation quotes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.