SO-40264078
by David Thomas
HTML
<div id="alpha">
<div>
<button id="q" class="letters">Q</button>
</div>
<div>
<button id="w" class="letters" onclick="theclick()">W</button>
</div>
<div>
<button id="e" class="letters">E</button>
</div>
<div>
<button id="r" class="letters">R</button>
</div>
<div>
<button id="t" class="letters">T</button>
</div>
<div>
<button id="y" class="letters">Y</button>
</div>
</div>
<textarea id="result"></textarea>
CSS
div > div {
text-align: center;
}
div > button {
width: 30%;
text-align: center;
}
JavaScript
// creating a named function to act as the event-handler:
function buttonOutput() {
// 'let' changed to 'var':
var textarea = document.querySelector('#result');
textarea.textContent += this.textContent.trim();
}
// here we retrieve the <button> elements with the class
// of 'letters' from the document:
let buttons = document.querySelectorAll('button.letters'),
// here we convert the Array-like NodeList into an Array,
// using Function.prototype.call() and Array.prototype.slice():
buttonArray = Array.prototype.slice.call(buttons);
// using Array.prototype.forEach() to iterate over the
// Array of <button> elements:
buttonArray.forEach(function(button) {
// button is the current Array-element of the
// Array over which we're iterating.
// here we assign the buttonOutput() function
// as the event-handler for the 'click' event:
button.addEventListener('click', buttonOutput)
});