[javascript] How to copy text from a div to clipboard

Here is my code for when the user clicks on this button:

<button id="button1">Click to copy</button>

How do I copy the text inside this div?

<div id="div1">Text To Copy</div>

This question is related to javascript jquery

The answer is


Both examples work like a charm :)

  1. JAVASCRIPT:

    _x000D_
    _x000D_
    function CopyToClipboard(containerid) {_x000D_
      if (document.selection) {_x000D_
        var range = document.body.createTextRange();_x000D_
        range.moveToElementText(document.getElementById(containerid));_x000D_
        range.select().createTextRange();_x000D_
        document.execCommand("copy");_x000D_
      } else if (window.getSelection) {_x000D_
        var range = document.createRange();_x000D_
        range.selectNode(document.getElementById(containerid));_x000D_
        window.getSelection().addRange(range);_x000D_
        document.execCommand("copy");_x000D_
        alert("Text has been copied, now paste in the text-area")_x000D_
      }_x000D_
    }
    _x000D_
    <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>_x000D_
    <br /><br />_x000D_
    <div id="div1">Text To Copy </div>_x000D_
    <br />_x000D_
    <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
    _x000D_
    _x000D_
    _x000D_

  2. JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard


Create a element to be appended to the document. Set its value to the string that we want to copy to the clipboard. Append said element to the current HTML document. Use HTMLInputElement.select() to select the contents of the element. Use Document.execCommand('copy') to copy the contents of the to the clipboard. Remove the element from the document

function copyToClipboard(containertext) {
    var el = document.createElement('textarea');
    el.value = containertext;
    el.text = containertext;
    el.setAttribute('id', 'copyText');
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    var coptTextArea = document.getElementById('copyText');
    $('#copyText').text(containertext);
    coptTextArea.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    /* Alert the copied text */
    alert("Copied : "+containertext, 1000);
}

I was getting selectNode() param 1 is not of type node error.

changed the code to this and its working. (for chrome)

_x000D_
_x000D_
function copy_data(containerid) {_x000D_
  var range = document.createRange();_x000D_
  range.selectNode(containerid); //changed here_x000D_
  window.getSelection().removeAllRanges(); _x000D_
  window.getSelection().addRange(range); _x000D_
  document.execCommand("copy");_x000D_
  window.getSelection().removeAllRanges();_x000D_
  alert("data copied");_x000D_
}
_x000D_
<div id="select_txt">This will be copied to clipboard!</div>_x000D_
<button type="button" onclick="copy_data(select_txt)">copy</button>_x000D_
<br>_x000D_
<hr>_x000D_
<p>Try paste it here after copying</p>_x000D_
<textarea></textarea>
_x000D_
_x000D_
_x000D_


<div id='myInputF2'> YES ITS DIV TEXT TO COPY  </div>

<script>

    function myFunctionF2()  {
        str = document.getElementById('myInputF2').innerHTML;
        const el = document.createElement('textarea');
        el.value = str;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('Copied the text:' + el.value);
    };
</script>

more info: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f


Adding the link as an Answer to draw more attention to Aaron Lavers' comment below the first answer.

This works like a charm - http://clipboardjs.com. Just add the clipboard.js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.


I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work. After trying I got to:

    <html>
        <body>
            <div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
            <script>
                function copyDivToClipboard() {
                    var range = document.createRange();
                    range.selectNode(document.getElementById("a"));
                    window.getSelection().removeAllRanges(); // clear current selection
                    window.getSelection().addRange(range); // to select text
                    document.execCommand("copy");
                    window.getSelection().removeAllRanges();// to deselect
                }
            </script>
        </body>
    </html>

Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)

Update March 27th, 2019.

For some reason document.createRange() didn't work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0).


This solution add the deselection of the text after the copy to the clipboard:

function copyDivToClipboard(elem) {
    var range = document.createRange();
    range.selectNode(document.getElementById(elem));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
}

The accepted answer does not work when you have multiple items to copy, and each with a separate "copy to clipboard" button. After clicking one button, the others will not work.

To make them work, I added some code to the accepted answer's function to clear text selections before doing a new one:

function CopyToClipboard(containerid) {
    if (window.getSelection) {
        if (window.getSelection().empty) { // Chrome
            window.getSelection().empty();
        } else if (window.getSelection().removeAllRanges) { // Firefox
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) { // IE?
        document.selection.empty();
    }

    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select().createTextRange();
        document.execCommand("copy");
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
        document.execCommand("copy");
    }
}

Non of all these ones worked for me. But I found a duplicate of the question which the anaswer worked for me.

Here is the link

How do I copy to the clipboard in JavaScript?


Made a modification to the solutions, so it will work with multiple divs based on class instead of specific IDs. For example, if you have multiple blocks of code. This assumes that the div class is set to "code".

<script>
        $( document ).ready(function() {
            $(".code").click(function(event){
                var range = document.createRange();
                range.selectNode(this);
                window.getSelection().removeAllRanges(); // clear current selection
                window.getSelection().addRange(range); // to select text
                document.execCommand("copy");
                window.getSelection().removeAllRanges();// to deselect
            });
        });
    </script>