How do I make a button that selects and copies to clipboard?

I’ve looked it up and tried a lot of different websites, and it works when I copy-paste it into its own file.
image

But when I try to import it into my own project, it tells me that .select() isn’t a function

Code of original:

<input type="text" id="code" size="20" value="Hello world!">
<button onclick="selectText()">Select text</button>

<script>
function selectText() {
  const copy = document.getElementById('code');
  copy.focus();
  copy.select();
  document.execCommand("copy");
}
</script>

The code around it in my project:

...
	<p id="code">
		\begin{array}{|l|l|} \hline <br>
		\text{0,0} & \text{0,1} \\\hline <br>
		\text{1,0} & \text{1,1} \\\hline <br>
		\end{array}
	</p>
	<button onclick="selectText()">Copy</button>
	</div>
</body>
<script src="code.js"></script>
<script>
function selectText() {
  const copy = document.getElementById('code');
  copy.focus();
  copy.select();
  document.execCommand("copy");
}
</script>
</html>

I even put it in the project’s HTML file itself just to make sure I didn’t mess up connecting the two files somehow.
I’m really confused, please help!

(Link to the un-updated project and repo)

The select method is on HTMLInputElement. You have a p element.

The HTMLInputElement.select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.

If you just want the text content of the element you can use innerHTML or innerText.

1 Like