12

I'm trying to copy the code written inside a <pre> tag into the clipboard. How can I do that? I have tried to solve this problem using the code below:

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.value);
}
<pre id="myInput">
  <span style="color:#97EDDC;">class </span>first
    {
        <span style="color:#97EDDC;">public</span> <span style="color:#97EDDC;">static </span> <span style="color:#97EDDC;">void </span> main(String args[]) // here S is capital of String word
        {
            System.out.println("Hello World!!"); // here S is capital of System word
        }
    }
</pre>

Give me the proper solution to copy code from pre tag into clipboard without including span tags.

Seth B
  • 944
  • 5
  • 19
Suyog
  • 375
  • 1
  • 3
  • 14

1 Answers1

24

Unfortunately, select() can only be used on visible input elements. So what you can do is extract the text content of pre element.

Apply this to textarea and position the textarea outside the normal view area.

function copyFunction() {
  const copyText = document.getElementById("myInput").textContent;
  const textArea = document.createElement('textarea');
  textArea.textContent = copyText;
  document.body.append(textArea);
  textArea.select();
  document.execCommand("copy");
}

document.getElementById('button').addEventListener('click', copyFunction);
textarea {
  position: absolute;
  left: -100%;
}
 
            
<pre id="myInput">
<span style="color:#97EDDC;">class </span>first
{
    <span style="color:#97EDDC;">public</span> <span style="color:#97EDDC;">static </span> <span style="color:#97EDDC;">void </span> main(String args[])
    {
        System.out.println("Hello World!!"); 
    }
}
            </pre>

<button id="button">Copy</button>
Agney
  • 13,998
  • 5
  • 36
  • 61