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>