Solution 1 :

I used this method and it worked:

function CopyToClipboard(id){
    var r = document.createRange();
    try {
        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.

Solution 2 :

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.setSelectionRange(0, 99999);

  // copy to the clipboard

  // 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>

Problem :

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");
    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??


Comment posted by How do I copy to the clipboard in JavaScript?

Does this answer your question?