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');
}