JavaScript JavaScript and the DOM Making Changes to the DOM Get and Set Content with textContent and innerHTML

"Cannot read properties of null (reading 'addEventListener')"

I cannot get this to run for the life of me, no matter how many times I've carefully retyped it all based on what Guil has, I ALWAYS get the above error in the console. Please tell me what I'm missing?

const btnUpdate = document.querySelector('.btn-main');

btnUpdate.addEventListener('click', () => {
  const headline = document.getElementById('headline');
  const input = document.querySelector('.input-main');

  headline.textContent = input.value;
  input.value = '';
});

5 Answers

Rachel Johnson
STAFF
Rachel Johnson
Treehouse Teacher

Hey Brady! This usually happens if we try to select an element and nothing matches our query. Can I get you to check if the Update Button in the HTML has a class of btn-main in your project? It might be named something else or it could maybe be an ID instead.

Rachel Johnson
Rachel Johnson
Treehouse Teacher

Also, since you're a Techdegree student, feel free to ping us on Slack with these questions too!

Oh wait the 'btn-main' is an ID not a class!

Rachel Johnson
Rachel Johnson
Treehouse Teacher

Yup! So the query selector should be #btn-main :D

Thanks Rachel! I'll probably finish the thread up here but on future questions I'll use the Slack.

Ok so double checking the HTML the input button is in fact class="input-main", I also tried targeting it by ID with .getElementById('main') with the same results....

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript and the DOM</title>
    <link href="css/style.css" rel="stylesheet">
  </head>
  <body>
    <div class="wrapper">
      <header>
        <h1 id="headline">My Day</h1>
        <div class="group">
          <label for="main">What's your task?</label>
          <input type="text" id="main" class="input-main">
          <button id="btn-main">Update Heading</button>
        </div>
      </header>

      <button class="btn-toggle">Hide List</button>

      <div class="list-container">
        <ul aria-live="polite">
          <li class='highlight'>Make coffee</li>
          <li>Practice JavaScript</li>
          <li class='highlight'>Walk the cat</li>
          <li>Watch a Treehouse video</li>
          <li>Go swimming</li>
          <li class='highlight'>Play my guitar</li>
        </ul>
        <button class="btn-remove">Remove Last Task</button>
      </div>
    </div>

    <script src="app.js"></script>
  </body>
</html>

I just ran into the same issue, and found the comments section after an hour of troubleshooting... I guess this is part of the training to see if we're paying attention?

FYI this issue is still present 10 months later.