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

Nebojsa Stevanovic
seal-mask
.a{fill-rule:evenodd;}techdegree
Nebojsa Stevanovic
Full Stack JavaScript Techdegree Student 9,620 Points

Hello.. i keep getting this error " java.js:3 Uncaught TypeError: Cannot read property 'addEventListener' of null "

Hello.. i keep getting error " Cannot read property 'addEventListener' of null "

i have spent 3 hours staring in the screen trying to see what's wrong but i gave up.. coud someone tell me whats wrong in this :

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel='stylesheet' href='style.css'> <script src='java.js'></script> <title>Document</title> </head>

<body> <h1 id='myHeading'>JavaScript and DOM</h1> <p> Making a web page interactive</p> </body> </html>

and my javascript code :

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

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

1 Answer

You are receiving that error because the script runs before the document finishes loading. I moved the script to the end of the body and it runs from there.

<body>
  <h1 id='myHeading'>JavaScript and DOM</h1>
  <p> Making a web page interactive</p>
  <script src='java.js'></script>
</body>