Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!