1

I tried this code but it doesn't work. How can I copy the code inside the <code> tag to the clipboard?

 <pre id="myCode">
   <code>
      console.log("hello world!")
   </code>
 </pre>

JavaScript

function copyScript(){
 document.getElementById('myCode').select();
 document.execCommand('copy');
}
tony19
  • 125,647
  • 18
  • 229
  • 307
  • 1
    Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – NicoCaldo Mar 31 '21 at 20:05

2 Answers2

1

The select() function can only be used on input elements such as <textarea> or <input>.

If you want to use it with your <code> tag, one way to accomplish it would be to copy the contents of the tag into a new <textarea> object and copy from that:

function copyScript() {
    // get the text to copy
    var codeText = document.getElementById('myCode').textContent;
    
    // create a textarea with the text we want to copy and add it to the page
    var textArea = document.createElement('textarea');
    textArea.textContent = codeText;
    document.body.append(textArea);
    
    // focus on the new textarea and copy the contents!
    textArea.focus();
    textArea.select();
    document.execCommand('copy');
}
newfurniturey
  • 37,556
  • 9
  • 94
  • 102
1

I would just do this for modern browsers

function copyToClipboard {
    let codeText = document.getElementById('myCode').textContent;
    // copying
    navigator.clipboard.writeText(codeText)
}
Mudassar
  • 508
  • 4
  • 13