I have this HTML script which displays some text on a webpage, with a button that allows you to copy the text to your clipboard:
<pre style="color: #000; background: #cccccc; padding:10px; display: inline-flex" id="TextToCopy">
select * from database.table where amount < 100</pre>
<button style="display: grid" onclick="copyToClipboard()">Click to Copy</button>
<script>
function copyToClipboard() {
var copyText = document.getElementById("TextToCopy");
navigator.clipboard.writeText(copyText.innerHTML);
}
</script>
When you run this on a webpage the text is displayed as it should. But when you click the button to copy the text, and then PASTE it somewhere you'll see <
instead of <
I realize why this is. In HTML, a less-than sign is written as <
, etc. But is there any way I can fix my script to be able to copy the text in the tags EXACTLY as they are?
By the way, I do need to keep the tag to display multi-line text that is indented.
Thank you in advance
An alternative to innerHTML
would be innerText
<pre style="color: #000; background: #cccccc; padding:10px; display: inline-flex" id="TextToCopy">
select * from database.table where amount < 100</pre>
<button style="display: grid" onclick="copyToClipboard()">Click to Copy</button>
<script>
function copyToClipboard() {
var copyText = document.getElementById("TextToCopy");
navigator.clipboard.writeText(copyText.innerText);
}
</script>