I have the below HTML
code and I'm wanting to copy the innerText of each p element, to the clipboard, using Javascript. The innerText value is generated dynamically and randomly.
<div class="colour-palette-showcase">
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text"></p>
</div>
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text"></p>
</div>
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text"></p>
</div>
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text"></p>
</div>
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text"></p>
</div>
</div>
I've stored the .colour-value-text
to a variable, run a forEach
and stored that to a new variable. But when I then try document.execCommand('copy')
, it loops through and only copies the last one.
I'm guessing I need to store all the values to one array and then copy that to the clipboard. Or am I going about this the wrong way?
Any help much appreciated. This is my first attempt at a little JS project.
Thank you
This is an example of code that copies all the <p>
's innerHTML to an array and from the array to a temporary textarea
from where the complete value is copied to your clipboard:
document.getElementById('copy-button').onclick = function() {
let values = [];
document.querySelectorAll('.colour-value-text').forEach( (p) => values.push( p.innerHTML ) );
let text = document.createElement('textarea');
document.body.appendChild(text);
text.value = values.join(', ');
text.select();
document.execCommand('copy');
text.parentNode.removeChild(text);
}
<div class="colour-palette-showcase">
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text">1</p>
</div>
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text">2</p>
</div>
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text">3</p>
</div>
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text">4</p>
</div>
<div class="colour-value">
<div class="colour"></div>
<p class="colour-value-text">5</p>
</div>
</div>
<button id="copy-button" type="button">copy</button>
Copied to clipboard:
1, 2, 3, 4, 5