Reputation: 1004
I use the floowing javascript to copy the text from all (multiple) code
elements on a webpage:
<p id="p1">Copy all code</p>
<button onclick="copyToClipboard('code')">Copy TEXT 1</button>
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
This is useful because if there are many code snippets on the page, and you want all of them, you do not have to copy them one by one. However it would be nice to separate the code copied with a blank line.
For example if I have:
<code>This is code snippet 1
</code>
<code>This is code snippet 2
</code>
The following will be copied to the clipboard:
This is code snippet 1This is code snippet 2
What I need is a line shift between the code like this:
This is code snippet 1
This is code snippet 2
As you probably guessed I want to do this without altering the content of the code
snippets.
Upvotes: 0
Views: 564
Reputation: 10081
Assuming the different pieces of <code>
can be anywhere in the document…
Here is the code I ended up with:
function copyToClipboard(element) {
var $temp = $("<textarea>");
$("body").append($temp);
var test = "";
$(element).each(function(index, item){
if(index > 0){
test = test + "\n";
}
test = test + item.innerHTML;
});
console.log(test);
$temp.val(test).select();
document.execCommand("copy");
$temp.remove();
}
code{
display: block;
border: 1px solid gray;
margin: 4px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code>This is code snippet 1</code>
<code>This is code snippet 2</code>
<button onclick="copyToClipboard('code')">Copy all code</button>
Hope it helps.
Upvotes: 0