Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
220,634 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. :-)