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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


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.


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


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

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

}, false);





Possible duplicate of How do I copy to the clipboard in JavaScript?
– Mehdi Dehghani
16 mins ago




3 Answers
3



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


<input>


<h3>



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


#p1


select



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 1004</h3>
<div style="opacity:0">
<textare type="text" id="copyText"/>
</div>
</div>





Oh ye this would work for sure! Thanks! Any reason why h3 doesn't work by it self?
– Fig
50 secs ago



Clipboard js will be helpfull in your case



I don't want to use external libraries and plugins as this problem should be solvable






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived