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

Whats wrong with my javascript?

I'm trying to add a class to an element to trigger an animation on a button click.

document.getElementsByClassName('button')[0].addEventListener('click',function(){
  document.getElementsByClassName('box')[0].className = 'active';
});

errors I get are:

Uncaught TypeError: Cannot set property 'className' of null

Uncaught TypeError: Cannot set property 'className' of undefined at HTMLDivElement.<anonymous>

1 Answer

Here you are overwriting the class name 'box' with the class name 'active'.

document.getElementsByClassName('box')[0].className = 'active';

On subsequent clicks the element 0 with class name 'box' no longer exists which is why you receive this error:

Cannot set property 'className' of undefined at HTMLDivElement.<anonymous>

So instead of setting the class name you could try to add an 'active' class to the element as follows:

document.getElementsByClassName('box')[0].classList.add('active');

The first part of your answer is what I suspected, since the element I was wanting to change the class of literally disappeared when I clicked the button. That makes sense seeing how you worded it, thank you.

The second part of your answer was awesome, thanks! That's the way I should have done it. I could use .classList.toggle and even gotten more use out of the button too. :)