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 syntax..

Ive wrote this very simple code that is suppose to alert you whenever you click a td element on the page. However it spits an Uncaught TypeError: board.addEventListener is not a function. Can someone explain why this is?

const board = document.querySelectorAll("td");
board.addEventListener("click", () => {
    alert("test");
});

board is a list of td elements. (array) The array does not know the addEventListener function. What you should do instead is add the event listener to the table.

const board = document.querySelector('.myBoard'); //where .myBoard is the table
board.addEventListener("click", (e) =>{
           //e will have access to the actual td that was clicked,....I believe via target. You can log it out and experiment with it
});

This process is called event delegation if you want to look more into it.

Got it, ty so much

1 Answer

Steven Parker
Steven Parker
243,656 Points

The delegated handler as suggested by Alexander is a good idea, but it needs a bit more implementation:

const board = document.querySelector("table");
board.addEventListener("click", e => {
    if (e.target.tagName == "td") {    // respond only to "td" elements
        alert("test");
    }
});

Note that with the generic "table" selector, only the first table of the page will be affected.