How to copy text from a div to clipboard

JavascriptJquery

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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).

Solution 2 - Javascript

Both examples work like a charm :)

  1. JAVASCRIPT:

    function CopyToClipboard(containerid) { 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"); alert("Text has been copied, now paste in the text-area") } }

    Text To Copy

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

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

function copy_data(containerid) {
  var range = document.createRange();
  range.selectNode(containerid); //changed here
  window.getSelection().removeAllRanges(); 
  window.getSelection().addRange(range); 
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
  alert("data copied");
}

<div id="select_txt">This will be copied to clipboard!</div>
<button type="button" onclick="copy_data(select_txt)">copy</button>
<br>
<hr>
<p>Try paste it here after copying</p>
<textarea></textarea>

Solution 5 - Javascript

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();
}

Solution 6 - Javascript

<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

Solution 7 - Javascript

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.

Solution 8 - 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>

Solution 9 - Javascript

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

https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript

Solution 10 - Javascript

The solutions above do not work for the content editable div. A few more steps are needed to copy its content to the clipboard.

Here is how to copy div contenteditable to the clipboard. Selecting text on the iphone and Android is not always easy. With one Copy button you can copy all the content.

<div id="editor1" contenteditable="true"></div> 

<button id="button1" onclick="CopyToClipboard()">COPY</button>

<script>

function CopyToClipboard() {

    var copyBoxElement = document.getElementById('editor1');
    copyBoxElement.contenteditable = true;
    copyBoxElement.focus();
    document.execCommand('selectAll');
    document.execCommand("copy");
    copyBoxElement.contenteditable = false;
    alert("Text has been copied")
}

</script>

Solution 11 - Javascript

Create a

Solution 12 - Javascript

const copyToClipboard = (id) => {
  var r = document.createRange();
  r.selectNode(document.getElementById(id));
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(r);
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
};

const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

const copyIOS = (id) => {
  const text = document.getElementById(id).innerHTML;

  if (!navigator.clipboard) {
    const textarea = document.createElement("textarea");

    textarea.value = text;
    textarea.style.fontSize = "20px";
    document.body.appendChild(textarea);

    const range = document.createRange();
    range.selectNodeContents(textarea);

    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    textarea.setSelectionRange(0, 999999);

    document.execCommand("copy");

    document.body.removeChild(textarea);
  }

  navigator.clipboard.writeText(text);
};

const copyTextById = (id) => {
  if (isIOS) {
    return copyIOS(id);
  }
  copyToClipboard(id);
};

window.copyTextById = copyTextById

<div id="text">Text which you will copy</div>

<button onclick="copyTextById('text')">Click me</button>

Above you can see really working code which will be working , on different browsers , also ios included

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavascriptJ. GarcíaView Answer on Stackoverflow
Solution 2 - JavascriptEldho NewAgeView Answer on Stackoverflow
Solution 3 - Javascriptromin21View Answer on Stackoverflow
Solution 4 - JavascriptArun TomView Answer on Stackoverflow
Solution 5 - JavascriptloretoparisiView Answer on Stackoverflow
Solution 6 - JavascriptOsowoIAMView Answer on Stackoverflow
Solution 7 - JavascriptAparnaView Answer on Stackoverflow
Solution 8 - JavascriptAmaliaKalioView Answer on Stackoverflow
Solution 9 - JavascriptiamafashaView Answer on Stackoverflow
Solution 10 - Javascriptuser4822420View Answer on Stackoverflow
Solution 11 - JavascriptSayed AzharuddinView Answer on Stackoverflow
Solution 12 - JavascriptAndrey RadkevichView Answer on Stackoverflow