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() {
// to support older browsers you may need to declare
// your variables with 'var' rather than 'let';
// here we cache the textarea, via its id attribute:
let textarea = document.querySelector('#result');
// and here we update the textContent of that
// textarea to the existing textContent with the
// addition of the newly-clicked element (the
// 'this' is the <button> element and is passed
// from the EventTarget.addEventListener() method)
// after calling String.prototype.trim() on that
// textContent (to remove leading and trailing
// white-space):
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 Array.from():
buttonArray = Array.from(buttons);
// using Array.prototype.forEach() to iterate over the
// Array of <button> elements:
buttonArray.forEach(
// 'button' is the current array-element of the Array
// over which we're iterating; here we bind the
// buttonOutput() function as the event-handler for
// the 'click' event (note the deliberate lack of
// parentheses in the function name):
button => button.addEventListener('click', buttonOutput)
);