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 Select a Page Element By Its ID

nathan goel
nathan goel
7,410 Points

addEventListener doesn't work for me...

I try to reproduce what I learn in this video, something doesn't work for me. I have a button with an id and I try to change it's color when clicked (using getElementById and addEventListener in my javascript file.) For some reason it doesn't work, can someone find the problem?

here is my relevant code in my html file:

<button id="basicButton">Change the background color</button>

in my js file:

const basicButton = document.getElementById("basicButton");

basicButton.addEventListener('click', () => { basicButton.style.color = 'red'; })

1 Answer

Jeremy Lapine
Jeremy Lapine
15,247 Points

Your code worked just fine for me if there is an issue it is that the button text reads "Change the background color" but the style you are targeting is the one that changes the text color. If you want it to change the background color of the button change it to basicButton.style.backgroundColor = 'red';.

If you aren't actually seeing any change to the button, either its text color or background color changing to red I wonder if you're using a browser that doesn't support ES2015 yet? You could always test that by using some older JavaScript and seeing if that works.

var basicButton = document.getElementById("basicButton");

    basicButton.addEventListener('click', function() {
      basicButton.style.backgroundColor = 'red';
    });