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

Rod R
Rod R
3,047 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

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 46,265 Points

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

 <h1 id="myHeading">
document.getElementById('myheading');
jlampstack
jlampstack
17,747 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!

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.