The select()
method is specifically designed for input elements like <textarea>
or <input>
.
If you wish to implement it with your <code>
tag, one approach would be to copy the content of the tag into a new <textarea>
element and then proceed with copying from there:
function duplicateCode() {
// store the text to duplicate
var codeContent = document.getElementById('myCode').textContent;
// create a textarea containing the desired text and place it on the page
var textareaElement = document.createElement('textarea');
textareaElement.textContent = codeContent;
document.body.append(textareaElement);
// focus on the newly created textarea and select its contents for copying
textareaElement.focus();
textareaElement.select();
document.execCommand('copy');
}