What is the difference between using classname, classList.toggle() and classList.add()?

Asked

Viewed 228 times

-2

I tested and the result was the same using the property className and the method classList.toggle:

  • So what is the advantage and disadvantage of using?

Using the className:

var btnSignin = document.querySelector("#signin");
var btnSignup = document.querySelector("#signup");
var body = document.querySelector("body");
      
btnSignin.addEventListener("click", function () {
  body.className = "sign-in-js"; 
});
    
btnSignup.addEventListener("click", function () {
  body.className = "sign-up-js";
});

Using the classList.toggle():

var btnSignin = document.querySelector("#signin");
var btnSignup = document.querySelector("#signup"); 
var body = document.querySelector("body");
    
btnSignin.addEventListener("click", function () {
  body.classList.toggle("sign-up-js");
});
    
btnSignup.addEventListener("click", function () {
  body.classList.toggle("sign-up-js");
});

1 answer

4

The estate className is a string that contains all classes of an element. For example:

const el = document.querySelector('div');

console.log(el.className); //=> foo bar baz

// Se modificarmos a classe utilizando `className`,
// pode-se acabar perdendo todas as anteriores. Veja:
el.className = 'qux';

console.log(el.className); //=> qux
<div class="foo bar baz">...</div>

This means that className is nothing more than a simple string type property that corresponds directly to the attribute class of an element. You can add a class using operator +=, for example, but when you need alter a class or remove a class can get a little more complicated.

Already the method toggle belongs to the object classList of an element. It will insert the class if it does not exist and remove if it exists.

An example:

const el = document.querySelector('div');

console.log(el.className); //=> foo bar baz

// Irá remover a classe `bar`, uma vez que já existe.
el.classList.toggle('bar');

console.log(el.className); //=> foo baz

// Irá adicionar a classe `bar`, uma vez que não existe.
el.classList.toggle('bar');

console.log(el.className); //=> foo baz bar
<div class="foo bar baz">...</div>

Besides toggle, the object classList has several other "convenience" methods for handling classes, such as classList.add or classList.remove. There is no direct comparison between className and classList.toggle, since they perform different functions.

See documentation to learn more:

Browser other questions tagged

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