cgrouge cgrouge - 11 days ago 5
HTML Question

Click to copy all elements of a specific class into the clipboard?

I'm aware there are many solutions for a click to copy feature, one of the most popular seems to be clipboard.js but I have not found a solution that allows you to copy only elements that have a specific class.

For example:

<div class="wrapper">
<div class="copytext">I want to copy this text</div>
<div class="nocopytext">I don't want to copy this text</div>
<div class="copytext">I also want to copy this text<div>
</div>
<button>Copy only classes with copytext</button>


How can I create my script to select all classes "copytext" and copy it to my clipboard but leave out anything else?

Answer

Use the document.getElementsByClasName()

<div class="wrapper">
   <div class="copytext">I want to copy this text</div>
   <div class="nocopytext">I don't want to copy this text</div>
   <div class="copytext">I also want to copy this text<div>
</div>
<button onclick="copyText()">Copy only classes with copytext</button>
<div id="output"></div>
<script>
function copyText(){
  var outputText = "";
  var targets = document.getElementsByClassName('copytext');
  for(var i = 0; i < targets.length; i++) {
    outputText += targets[i].innerText;
  }
  var output = document.getElementById('output');
  output.innerText = outputText;
  var range = document.createRange();
  range.selectNodeContents(output);
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand('copy');
  output.style.display = 'none';
}
</script>
Comments