How to get text from h3 with native js?

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?

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *