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 trialseungwoo lee
2,562 PointsUncaught 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?
1 Answer
Umidjon Khaitov
8,884 PointsIt'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.
Jennifer Nordell
Treehouse TeacherJennifer Nordell
Treehouse TeacherGenerally, 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"
orid="myHeading"
. To troubleshoot this for you it's going to be easiest if we can see a snapshot of your workspace,