Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda