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 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'; });

Can you post your html?

2 Answers

Camilo Lucero
Camilo Lucero
27,692 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>
    <title>JavaScript and the DOM</title>
    <link rel="stylesheet" href="css/style.css">
    <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>