Answers for "apply function to all elements with a class name"

0

apply function to all elements with a class name

/*
The getElementsByClassName returns a array of elements (2 in your example),
so you'll have to loop through it and add the onclick event.
To access the current button inside the onclick event handler, use this.
You cannot pass whatever parameters you want to the function because its signature is fixed.
It gets passed a reference to the event itself, not the clicked element,
so the name clicked_button is deceiving. We usually call that parameter event,
or e for short. You can access the element using event.target, but using this is just easier.

*/

var value;
var buttons = document.getElementsByClassName('button');

for (var i = 0; i < buttons.length; i++) {
  buttons[i].onclick = selectValue;
}

function selectValue() {
  value = this.value;
  console.log(value);
}
Posted by: Guest on September-16-2021

Code answers related to "apply function to all elements with a class name"

Code answers related to "TypeScript"

Browse Popular Code Answers by Language