Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 732
Suyog Avatar asked Mar 05 '18 11:03

Suyog


People also ask

How do I copy something to the clipboard in HTML?

writeText() function. This function writes the data fed to it as a parameter into the clipboard. We can use this to copy any text to the clipboard. First, we select the text to copy to the clipboard whether it is from a div or from an input box using document.

How do I copy the same text in HTML?

Tip: There are three ways to copy an element/the content of an element: Press CTRL + C. Select "Copy" from the Edit menu in your browser. Right click to display the context menu and select the "Copy" command.


1 Answers

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>
like image 93
Agney Avatar answered Sep 19 '22 18:09

Agney