use classList.add

Asked

Viewed 98 times

0

I have two conditions in a pure javascript code; if the request sent via restful was received by the service I show on the screen a sentence in green color, if not, another sentence in red color. I’m trying to use classList.add for this, but I’m not getting results:

      let erro = "";
      erro = "Categoria já existente no sistema";
      document.querySelector(".categoria-aviso").innerHTML = erro;
      erro.classList.add('erro');

This way he is not displaying the text in red color. I thank those who help.

1 answer

2

Turns out you’re trying to add a class css in a string instead of an element and so is not working.

You must store the input with document.querySelector into a variable and then modify that variable.

Following example:

let erro = "";
erro = "Categoria já existente no sistema";
let span = document.querySelector(".categoria-aviso");
span.innerHTML = erro;
span.classList.add('erro');
.erro {
    color: red;
}
<span class="categoria-aviso"></span>

Browser other questions tagged

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