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

seungwoo lee
seungwoo lee
2,562 Points

Uncaught TypeError: Cannot read property 'addEventListener' of null

I followed your course

ex) const myButton = document.getElementById('myButton'); const myHeading = document.getElementById('myHeading'); myButton.addEventListener('click', () => { myHeading.style.color = 'red'; })

but it does not work...... error code is "app.js:3 Uncaught TypeError: Cannot read property 'addEventListener' of null"

why does not working?

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Generally, when we see that error it's because the DOM element is not getting selected properly. My instinct is to say that the problem is not in your JavaScript but rather in your HTML. It sounds like you might have a spelling error in your id="myButton" or id="myHeading". To troubleshoot this for you it's going to be easiest if we can see a snapshot of your workspace, :sparkles:

1 Answer

Umidjon Khaitov
Umidjon Khaitov
8,884 Points

It's just bcz your JS gets loaded before the HTML part and so it can't find that element. Just put your whole JS code inside a function which will be called when the window gets loaded.