I have several pieces of HTML within [pre] tags that I want to associate to a copy button with class 'bla'. My JS code below works for one [pre id="copyCodeOne"] BUT I need to copy several independently.. so [pre id="copyCodeTwo"]; [pre id="copyCodeThree"] etc .. What do I need to change on my JS below please?
Many thanks in advance.
// HTML
<code>
<pre id="copyCodeOne">
any html here
</pre>
</code>
// END HTML
// JS
var bttn = document.getElementsByClassName("bla");
for(var i = 0; i < bttn.length; i ) {
bttn[i].addEventListener('click', copyFunction, true);
}
// Copy code to clipboard
function copyFunction() {
const copyText = document.getElementById("copyCodeOne").textContent; // >>> I need several of these
const textArea = document.createElement('textarea');
textArea.textContent = copyText;
document.body.append(textArea);
textArea.select();
document.execCommand("copy");
};
// END JS
CodePudding user response:
Select by index
Use the index of the button to selected your pre elem like so :
<pre>
any html here
</pre>
function addListeners() {
const btns = document.getElementsByClassName("bla");
for(var i = 0; i < btn.length; i ) {
btns[i].addEventListener('click', (e) => copyFunction(i), true); // call function with idx
}
}
function copyFunction(idx) {
// use idx to select right 'pre' tag
const copyText = document.querySelectorAll('pre')[idx].textContent;
const textArea = document.createElement('textarea');
textArea.textContent = copyText;
document.body.append(textArea);
textArea.select();
document.execCommand("copy");
};
Here is a working Stackblitz.
Note: If you get 'cannot read textContent of undefined' it probably means that your 'pre' elems doesn't exist, or that you have more pre than buttons elements.
Cheers