0

How can I select textcontent before it is copied to the clipboard? Here is an idea of selecting with one click: https://stackoverflow.com/a/1173319. But this is an other code with id selector. I only want to select textcontent with a class before copy it. Below is the code that is used to make a copy (onclick element with class as classname):

spans = document.querySelectorAll(".class");
for (const span of spans) {
  span.onclick = function() {
    document.execCommand("copy");
  }

  span.addEventListener("copy", function(event) {
    event.preventDefault();
    if (event.clipboardData) {
      event.clipboardData.setData("text/plain", span.textContent);
    }
  });
}
<p class="class">
  p
</p>
<span class="class">
span
</span>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Do you mean, you want the element to be highlighted when you click it, so that it both gets highlighted and copied? – CertainPerformance Jan 25 '20 at 23:51
  • No CSS highlighting, but like when I mark it with the mouse. –  Jan 25 '20 at 23:52
  • 1
    You can use the solution in the answer you've mentioned, you just need to replace `document.getElementById(containerid)` with `span`. – Titus Jan 25 '20 at 23:55

0 Answers0