Warm tip: This article is reproduced from stackoverflow.com, please click
javascript jquery

How to copy text from a div to clipboard

发布于 2020-03-28 23:17:29

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>
Questioner
Alex
Viewed
20
598 2019-02-01 18:55

Both will works 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 copied") 
    }}
    

Also in html,

<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

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

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>

Here is the snippet.

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 copied, copy in the text-area")
  }
}
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

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

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>