apply function to all elements with a class name 1

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);
}

Here is what the above code is Doing:
1. Get all the buttons with the class name button.
2. Loop through the array of buttons and add an onclick event handler to each one.
3. The onclick event handler is the function selectValue.
4. The selectValue function sets the value variable to the value of the button that was clicked.
5. The selectValue function then logs the value to the console.

Similar Posts