Copy text in raw JavaScript

avatar
Published: Jan 10, 2023

Today I will show you how to copy a text or data in raw JavaScript.

<p id="copy_the_text" onlcick="copy()">Hello! Copy Me.</p>

Now, Here is the javascript code 👇

<script>
// copy code -------------------------------------------------------------------------------------------------------
    function copy() {
      let copyText = document.getElementById("copy_the_text").innerText;
      window.getSelection().removeAllRanges();
      const htmlCopyText = document.createElement('textarea');
      htmlCopyText.value = copyText;
      document.body.appendChild(htmlCopyText);
      htmlCopyText.select();
      document.execCommand('copy');
      document.body.removeChild(htmlCopyText);
    }
</script>