1

I have a basic question in JS. want to get the inner text of an element that the user clicked on.

I use

document.querySelectorAll(".key")

to get all the elements with the class key, and put event listener on them.

I want to know after the user click on one of them the inner html, and I get

TypeError: elements.addEventListener is not a function

I know this is basic but I am not understand what is wrong. this is my script

<script>
    
   var elements = document.querySelectorAll(".key");
   elements.addEventListener("click", function(e) {
      console.log(e.target.innerText);
   })
  
    </script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Bastian
  • 1,089
  • 7
  • 25
  • 74
  • 1
    Does this answer your question? [addEventListener on a querySelectorAll() with classList](https://stackoverflow.com/questions/50643302/addeventlistener-on-a-queryselectorall-with-classlist) – Achtung Aug 12 '21 at 20:42
  • 1. querySelectorAll returns a collection 2. DELEGATE: find the closest static container - let's call it `id="myKeyContainer"` and do `document.getElementById("myKeyContainer").addEventListener("click", function(e) { const tgt = e.target; if (tgt.classList.contains("key")) console.log(tgt.textContent); })` – mplungjan Aug 12 '21 at 20:44
  • TNX Achtung it solved it – Bastian Aug 12 '21 at 20:55

1 Answers1

2

document.querySelectorAll() returns multiple items. Maybe you want to add a listener to each item.

var elements = document.querySelectorAll(".key");
   elements.forEach(element => {
    element.addEventListener("click", function(e) {
      console.log(e.target.innerText);
    });
   });
<button class="key">Hello</button>
<button class="key">Hello2</button>
<button class="key">Hello3</button>
AaronJ
  • 1,060
  • 10
  • 24