How can I copy <pre> tag code into clipboard in HTML?

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.

16 thoughts on “How can I copy <pre> tag code into clipboard in HTML?”

Leave a Comment