0

I have multiple HTML buttons with the same class="preis".

<button class="preis" value="4,50">4,50€</button>
<button class="preis" value="5,50">5,50€</button>
<button class="preis" value="3,00">3,00€</button>

I want to output the value of the exact button I clicked in the console.log. I've tried this so far:

function output() {
    console.log(price.value);
}

var price = document.getElementsByClassName("preis");
price.addEventListener("click", output, true);

and I want to avoid using different IDs for each button if thats possible.

Bent1408
  • 5
  • 1
  • 3

1 Answers1

1

You can use forEach with querySelectorAll

function output() {
    console.log(this.value);
}

var price = document.querySelectorAll(".preis");
price.forEach(el =>{
  el.addEventListener("click", output, true);
});
<button class="preis" value="4,50">4,50€</button>
<button class="preis" value="5,50">5,50€</button>
<button class="preis" value="3,00">3,00€</button>

Reference:

-Array.prototype.forEach()
-Document.querySelectorAll()

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34