Search code examples
javascriptcopyclipboard

Copy to clipboard is not a function when copying text inside h3 tag


I'm trying to copy text to clipboard that is inside a h3 tag. I get the following error at the copyText.select() code line.

Uncaught TypeError: copyText.select is not a function at HTMLDivElement.

edit: When using on a input-tag the copy to clipboard function works, but not when inside h3 tag.

HTML

<div class="colorDiv" id="firstColorObject">
    <h3 class="colorCode" id="p1" value="123">#Color 1</h3>
</div>

JavaScript

document.querySelector("#firstColorObject").addEventListener("click", function(){
    var copyText = document.getElementById("p1");

    copyText.select();
    document.execCommand("copy");
    alert("Copied the text: " + copyText.value);

}, false);

Solution

  • You can call select with an <input>-element but not with a <h3>-element.

    Nevertheless you can take advantage of <input> when you assign the content of #p1 to a hidden field before calling select with it.

    Note that: Calling select with an hidden field only works when you wrap an actually visible field around a <div>-element that is hidden (only tested with opacity:0). A value could not be copied (through select and document.execCommand("copy")) from a truly hidden input like this:

    <input type="hidden" id="copyText"/>
    

    Hope my example below helps you (to execute it click on "Run Code snippet"-Button):

    document.querySelector("#firstColorObject").addEventListener("click", function(){
    
        var p1 = document.getElementById("p1");
        
        // set "#Color 1" with the hidden field so that you can call select on it
        var hiddenField = document.getElementById("copyText");
        hiddenField.value = p1.innerHTML;
        hiddenField.select();
        document.execCommand("copy");
        
        alert("Copied the text: " + hiddenField.value);
    
    }, false);
    <div class="colorDiv" id="firstColorObject">
        <h3 class="colorCode" id="p1" value="123">#Color 1</h3>
        <div style="opacity:0">
            <input type="text" id="copyText"/>
        </div>
    </div>