JavaScript JavaScript and the DOM Getting a Handle on the DOM Select a Page Element By Its ID

nathan goel
nathan goel
7,281 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';
    });