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
behar
10,800 PointsJavascript 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");
});
behar
10,800 PointsGot it, ty so much
1 Answer
Steven Parker
243,656 PointsThe 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.
Alexander La Bianca
15,960 PointsAlexander La Bianca
15,960 Pointsboard 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.
This process is called event delegation if you want to look more into it.