I used this method and it worked:
function CopyToClipboard(id){
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
try {
document.execCommand('copy');
window.getSelection().removeAllRanges();
console.log('Successfully copy text: hello world ' + r);
} catch (err) {
console.log('Unable to copy!');
}
}
<div id="div_id">Hello World From div Content</div>
<button type="button" onclick="CopyToClipboard('div_id')">Copy text</button>
i got this code from here.
I have only been able to copy text from <input>
and <textarea>
. So my strategy was to copy the text from the <div>
to a invisible <textarea>
.
But I couldn’t get the copy.value to display in the alert properly (it cancelled the clipboard copy for some reason). So I just used the value of the copyText
function myFunction() {
// get the div contents
let copyText = document.getElementById("copy").innerHTML;
// get the textarea element
var copy = document.getElementById("copyTextarea");
// move the content from the div to the textarea
copy.value = copyText;
// select the content inside the textarea
copy.select();
copy.setSelectionRange(0, 99999);
// copy to the clipboard
document.execCommand("copy");
// alert
alert("Copied the text: " + copyText);
}
You’d need to create your <div>
and your <textarea>
:
<div id="copy" onclick="myFunction()">Simple Test</div>
<textarea style="display: none;" id="copyTextarea"></textarea>
i have a div
with id
copy
and a button.i want when that button is clicked i copy the div
content into the clipboard
function myFunction() {
var copyText = document.getElementById("copy");
copyText.innerHTML=html;
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
that is what i have tried so far but does not seem to work.
please help me.
how can i go about this??