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

Uncaught Type Error

the code:

const myHeading = document.getElementById('myHeading');

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

returns the error: Uncaught TypeError: Cannot read property 'addEventListener' of null at js.js:6

any ideas?

Steven Parker
Steven Parker
229,608 Points

To facilitate a complete analysis, always show the whole code (including the HTML part), or make a snapshot of your workspace and post the link to it here.

3 Answers

Dom Farnham
Dom Farnham
19,421 Points

Sounds like the DOM hasn't fully loaded before your js code is excecuted. Do you have you script tags at the bottom of the html page or top? If at the top, try moving them to the bottom before body closes. Let me know how you get on. Hope this helps. :-)

Thank you Dom.. that was indeed the solution. I had actually figured it out.. probably should of updated this thread. And Stephen, yes. I will from now on make sure i include ALL code when submitting help requests (and i'm sure they'll be a few requests submitted during my time with team treehouse :D)

Thanks again to both of u for your time

Dom Farnham
Dom Farnham
19,421 Points

No problem Richard. Anytime. :-)