I have this JS to copy each text in its respective textareas. Currently I have 3 textareas and 3 copy buttons, with 3 separate JS functions. How do I shorten my JS code?
var copyTextareaBtn0 = document.querySelector('.btn0');
var copyTextareaBtn1 = document.querySelector('.btn1');
var copyTextareaBtn2 = document.querySelector('.btn2');
copyTextareaBtn0.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.text0');
copyTextarea.focus();
copyTextarea.select();
var successful = document.execCommand('copy');
});
copyTextareaBtn1.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.text1');
copyTextarea.focus();
copyTextarea.select();
var successful = document.execCommand('copy');
});
copyTextareaBtn2.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.text2');
copyTextarea.focus();
copyTextarea.select();
var successful = document.execCommand('copy');
});
<textarea class="box text0" id="text0">Text 1</textarea>
<button class="btn0" style="vertical-align:top;">Copy</button>
<textarea class="box text1" id="text1">Text 2</textarea>
<button class="btn1" style="vertical-align:top;">Copy</button>
<textarea class="box text2" id="text2">Text 3</textarea>
<button class="btn2" style="vertical-align:top;">Copy</button>
2
Answers
You could use a structure like this. Or in html you can do it as follows by enclosing the elements in a div.
You could loop through all elements and add listeners to every element
this.parentNode
to get the parent of the clicked button.parent.querySelector('.text')
: to select the child(text area)