JavaScript JavaScript and the DOM Getting a Handle on the DOM Select a Page Element By Its ID

Malika Sinkler
Malika Sinkler
Full Stack JavaScript Techdegree Student 2,961 Points

I'm getting an Uncaught TypeError: Cannot read property 'addEventListener' of null. When clicking on the button.

const heading = document.getElementById('myHeading'); const button = document.getElementById('myButton');

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

2 Answers

Camilo Lucero
Camilo Lucero
26,506 Points

Your JavaScript code is fine, this error means that the variable button is not linking correctly to your button.

In this case, I think that your problem might be in your HTML file. Check that your are linking the JS file in the HTML file, using the <script> tag with the attribute src pointing to your JS file:

<!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>
    <button id="myButton">Change color</button>
    <script src="app.js"></script>
  </body>
</html>
Malika Sinkler
Malika Sinkler
Full Stack JavaScript Techdegree Student 2,961 Points

Hi Camilo, you are correct, it was a syntax error in my HTML file. Thanks for your response.