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?
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?
Share Improve this question edited Nov 22, 2016 at 16:13 cgrouge asked Nov 22, 2016 at 15:52 cgrougecgrouge 1873 silver badges18 bronze badges 4-
No idea whether this is doable. Workaround idea: 1. hide all the
nocopytext
elements 2. use clipboard.js to copy/cut 3. show the elements again – Pekka Commented Nov 22, 2016 at 15:55 - Possible duplicate of How do I copy to the clipboard in JavaScript? – pistou Commented Nov 22, 2016 at 15:56
- @pistou not really. The OP is arguably asking about something slightly more specific here. – Pekka Commented Nov 22, 2016 at 15:57
- @pistou that seems to only select the first class that shows up. – cgrouge Commented Nov 22, 2016 at 16:05
1 Answer
Reset to default 7Use the document.getElementsByClassName()
:
<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>