Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
How can I prevent adding duplicate classes to an HTML element?

How can I prevent adding more classes error while somebody is repeatedly clicking on the submit button? In Chrome Dev Tools I see that they keep being added more and more if you spam the button. I don't know how to prevent this.

function errorFunc(req, message) {
    const formControl = req.parentElement;
    const span = formControl.querySelector('span');
    span.innerText = message;
    req.className += 'error';
    span.className += 'error-text';
    if(req !== email) {
        req.value = ' ';
    } else {
        req.style.color = "hsl(0, 100%, 74%)";
    }
}

function successFunc(req) {
    req.className += 'success';
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use element.classList.add() which doesn't create duplicates.

const x = document.querySelector('.x');
x.classList.add('error');
console.log(x.className);
x.classList.add('error');
console.log(x.className);
<div class="x"></div>

ClassList is DOMTokenList and as the MDN documentation says:

Methods that modify the DOMTokenList (such as DOMTokenList.add()) automatically trim any excess Whitespace and remove duplicate values from the list.

about 4 years ago · Juan Pablo Isaza Relatório

0

can be done with simple use js internal classList of a element

/** @type {HTMLElement} */
let req = document.querySelector('.x');
req.classList.add('error')

this does not add the error class if it allready exists. and it's easier to remove the error class if not longer needed req.classList.remove('error') (only removes if class is present).

also you can check if the class you want to add already is existing

req.classList.has('error');

here is the manual

HTMLElement classList

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda