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 Making Changes to the DOM Create New DOM Elements

Katherine Seibel
Katherine Seibel
Full Stack JavaScript Techdegree Student 2,852 Points

Trouble with .addEventListener

Hi there! throughout this course as I follow along with Guil's code, I've been getting an error on line 4 and I can't seem to figure out how it's different and where I am going wrong.

This is what my code looks like currently:

const btnToggle = document.querySelector('.btn-toggle');
const btnCreate = document.querySelector('.btn-main');

btnCreate.addEventListener('click', () => {
  const input = document.querySelector('.input-main');
  const item = document.createElement('li');

  item.textContent = input.value;
  input.value = '';

Thank you so much!

3 Answers

Steven Parker
Steven Parker
229,582 Points

Now that I see the rest of the code, in the HTML file there is this line:

          <button id="btn-main">Add Task</button>

This creates a button with an id instead of a class, so the query won't find it. This can be fixed in either of two ways:

  • in the HTML by changing "id" to "class"
  • in the JavaScript by changing the query selector from ".btn-main" (class selector) to "#btn-main" (id selector)
Steven Parker
Steven Parker
229,582 Points

This code relies on the HTML part, and if that part is missing the button with the proper class name then this part will fail.

A much better way to share project code (all parts together) is to make a snapshot of your workspace and post the link to it here.