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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With