JavaScript JavaScript and the DOM Getting a Handle on the DOM A Simple Example

Rod R
Rod R
3,049 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', () => { = '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

54,287 Points

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

 <h1 id="myHeading">
22,750 Points

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!

kevin hudson
kevin hudson
Pro Student 9,652 Points

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.