htmlfunctionnavigatorpre

Ignore tags in <pre>, but also ignore them in a script


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 &lt; instead of <

I realize why this is. In HTML, a less-than sign is written as &lt;, 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


Solution

  • 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>