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 JavaScript and the DOM (Retiring) Getting a Handle on the DOM Selecting Elements with the Same Class Name

Vic Mercier
Vic Mercier
3,276 Points

Dom and class

There is a way to change the class name using only JavaScript?

2 Answers

Owa Aquino
Owa Aquino
19,277 Points

Hi Vic,

Yes, what you need is to get that DOM element and remove first it's (existing) class by classList.remove() method and then supply a new class with classList.add() method.

Check this out for more details: http://callmenick.com/post/add-remove-classes-with-javascript-property-classlist https://developer.mozilla.org/en/docs/Web/API/Element/classList

Hope this help! Cheers!

Stephan Olsen
Stephan Olsen
6,650 Points

You can use the classList property to add and remove a class. Example:

document.getElementsByClassName('originalClass').classList.add('newClassName');
document.getElementsByClassName('newClassName').classList.remove('originalClass');