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

270
Views
Difference between className and classList

Which one of the following should be preferred under what circumstances?

btnElement.classList.add('btn');

btnElement.className = 'btn';
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Using "classList", you can add or remove a class without affecting any others the element may have. But if you assign "className", it will wipe out any existing classes while adding the new one (or if you assign an empty string it will wipe out all of them).

Assigning "className" can be a convenience for cases where you are certain no other classes will be used on the element, but I would normally use the "classList" methods exclusively.

And "classList" also has handy "toggle" and "replace" methods.

https://teamtreehouse.com/community/difference-between-classlist-and-classname

about 4 years ago · Juan Pablo Isaza Report

0

ClassList as the name suggest is the list of classes in an element.

If you have multiple classes on an element and you want to add/remove one without altering the rest you should use classList.

classList also provides methods like toggle which are really useful.

function toggleClass(){
  let txt = document.querySelector("h2");
  txt.classList.toggle("changebg");
}
.font-style {
  font-family: sans-serif;
}

.changebg {
  background-color: lightcoral;
}
<h2 class="font-style" >Hello World!</h2>
<button onclick='toggleClass()'>Toggle Background Class</button>

about 4 years ago · Juan Pablo Isaza Report

0

I have just known one thing difference between className and classList. className returns string within they are names of the current element and classList also returns names but as an array.

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!