0

I have some h3 elements with the same class. I need to get text from h3 when i click on one of the elements.

document.querySelector(`.block__item__name`).onclick = function() {
  let value = this.textContent;
  console.log(value);
};

This code works with first h3 only. How can i fix it?

Gg Wp
  • 115
  • 1
  • 1
  • 8
  • `querySelector` will only match the first element found. See https://stackoverflow.com/questions/34482587/queryselectorall-not-working-with-onclick-event for a way to use `querySelectorAll` instead – j08691 Feb 18 '21 at 14:57
  • oh ok. So how to solve my problem? – Gg Wp Feb 18 '21 at 14:59
  • thx. I tried to use it but it didn't work. I think i did mistake somewhere – Gg Wp Feb 18 '21 at 15:03

2 Answers2

0

Per the documentation, querySelector gives you the first result for your query. If you want all results, use querySelectorAll

document.querySelectorAll(`.block__item__name`)forEach(item => {
  item.onclick = function() {
   let value = this.textContent;
   console.log(value);
  };
});
cloned
  • 6,346
  • 4
  • 26
  • 38
0
const content = document.getElementsByClassName("titel");

for (let i = 0; i < content.length; i++) {
  content[i].addEventListener("click", function () {
    let value = this.textContent;
    console.log(value);
  });
}

You can try it out here: https://jsitor.com/EKnmSAr5J