CopyFunction=()=> {
const elm = document.getElementById("copyCodeId");
// for Internet Explorer
if (document.body.createTextRange) {
const range = document.body.createTextRange();
range.moveToElementText(elm);
range.select();
document.execCommand("copy");
alert("Copied div content to clipboard");
} else if (window.getSelection) {
// other browsers
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(elm);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
alert("Copied div content to clipboard");
}
}
<div class="code-bg" id="copyCodeId">
Click on the button to copy the text from the div element. Try to paste the text<span style="color:red"> (e.g. ctrl+v)</span> afterwards in a different window, to see the effect.
</div>
<button onclick="CopyFunction()">Copy div</button>