Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Adding and Removing Names RSVP Checkbox

Difference between classList and className?

What's the difference between:

if (checked){
    listItem.classList.add('responded');
}else{
    listItem.classList.remove('responded');
}

AND

if (checked){
    listItem.className = 'responded';
}else{
    listItem.className = '';
}

Which is preferred? I am assuming the first option is great for when elements have many classes, and the second option is great if the element will only toggle between having a class and not having it...

Thanks!

1 Answer

Steven Parker
Steven Parker
231,236 Points

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.

Awesome! Thanks very much for the easy-to-understand explanation :)