Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
212,126 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 :)