0

I need to copy the text that is inside of ~p~ tag, I've tryed using this code:

HTML:

<p id="copy">Text to copy</p>
<button onclick="copyFunction()">Copy text</button>

JS:

function copyFunction() {
   var textToCopy = document.getElementById("copy");
   textToCopy.select();
   document.execCommand("copy");
   alert("Copied the text: " + textToCopy.value);
}

But it didn't worked.

Alfin Paul
  • 1,337
  • 8
  • 25
Max Steel
  • 21
  • 3

3 Answers3

2

function copyFunction() 
{
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($('#copy').text()).select();
    document.execCommand("copy");
    $temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="copy">Text to copy</p>
<button onclick="copyFunction()">Copy text</button>
Vijay Makwana
  • 896
  • 8
  • 23
0

You can also use window.clipboardData.setData("text/plain", Your text from p tag);

Simranjit Singh
  • 394
  • 1
  • 6
0

You can go like this. Not tested but it can work.

   const ptag = document.querySelector("p");

   ptag.onclick = function() {
      document.execCommand("copy");
   }

   ptag.addEventListener("copy", function(event) {
      event.preventDefault();
      if (event.clipboardData) {
         event.clipboardData.setData("text/plain", ptag.textContent);
         console.log(event.clipboardData.getData("text"))
      }
   });

Now click on the <p> tag. Text from that tag will be copied to your clipboard.

Keyur Ramoliya
  • 1,643
  • 2
  • 12
  • 14