-1

When I run this code, I get an error in the console that states 'button.addEventListener is not a function' and when I mouse over responseToClick in my text editor, it says the function is void. What am I doing wrong here?

const button = document.querySelectorAll("button");
const body = document.querySelector("body");
button.addEventListener('click', responseToClick)

function responseToClick() {
    const h3Tag = document.createElement('h3');
    h3Tag.textContent("Foo");
    body.appendChild(h3Tag);
}
  • 1
    The `.querySelectorAll()` method returns a **list** of elements. – Pointy Mar 21 '23 at 18:31
  • Use `const button = document.querySelector("button");` to only select the first occurence of a `button` in the DOM. Then, you can set up a handler for it. – Scott Marcus Mar 21 '23 at 19:38

1 Answers1

0

In 1st line, You are using querySelectorAll, Which returns an array. if there is only 1 button, here's the updated code:

const button = document.querySelector("button");
const body = document.querySelector("body");
button.addEventListener('click', responseToClick)

function responseToClick() {
    const h3Tag = document.createElement('h3');
    h3Tag.textContent("Foo");
    body.appendChild(h3Tag);
}
  • [`.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) does not return an array. It returns an ["array-like" object](https://www.oreilly.com/library/view/javascript-the-definitive/9781449393854/ch07s11.html), called a ["node list"](https://developer.mozilla.org/en-US/docs/Web/API/NodeList). – Scott Marcus Mar 21 '23 at 19:37