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 A Simple Example

Rod R
Rod R
3,050 Points

My code isnt working- please review

<!DOCTYPE html> <html> <head> <title>JavaScript and the DOM</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <h1 id="myHeading">JavaScript and the DOM</h1> <p>Making a web page interactive</p> <script src="app.js"></script> //verified this is linked by adding an alert </body> </html>

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

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

JS console error: Uncaught TypeError: Cannot read property 'addEventListener' of null at app.js:4

The click function to change the heading to red from black isn't working (from: JS > Javascript and the DOM > Getting a handle on the DOM > A Simple Example)

Thank you.

2 Answers

Note the case of h in heading. They are different between your script and html.

 <h1 id="myHeading">
document.getElementById('myheading');

You added the script in the head. Try adding near the end right before the closing body tag, same as instructor. I believe the reason for this is The Document needs to fully load before we can start selecting elements. If anyone can confirm that would be great!

You looked at this wrong. Rod was just copying and pasting his code to the post without using the backtick. So it's hard to read. The first answer is right he did a typo.