How to Copy Text wrapped in a <pre> tag to the Clipboard using JavaScript

Rezaul H Reza 29 December 2022 Component 5 minutes read

Welcome to this tutorial on how to copy text to the clipboard using JavaScript! The clipboard is a temporary storage area that holds data that you have copied or cut, so that you can paste it elsewhere.

To begin, let's take a look at the HTML code. We have two pre elements, each containing a string of text. The pre element is used to display text in a fixed-width font, preserving both spaces and line breaks.

Next, let's move on to the JavaScript code. The first function we'll look at is copyPreContent(). This function is called when the "Copy" button is clicked.

The first step in this function is to get the pre element that comes after the button (which is the element containing the text we want to copy). We do this using the nextSibling property of the button element.

Next, we get the text from the pre element using the textContent property. This property returns the text inside an element, including all its children, as a string.

Then, we use the clipboard API's writeText() method to copy the text to the clipboard. This method takes a string as an argument and returns a promise that resolves when the text has been successfully copied.

If the promise resolves successfully, we display an alert message to the user indicating that the text has been copied. If there is an error, we log it to the console.

Finally, we get all the pre elements in the body of the HTML document using the querySelectorAll() method and the pre element's tag name. We loop through each pre element and add a "Copy" button just before it using the insertBefore() method.


Example:


<!DOCTYPE html>
<html>
<head>
  <title>Copy Text to Clipboard</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
  <h1>Copy Text to Clipboard</h1>
  <p>Click the "Copy" button to copy the text in the pre element to the clipboard:</p>
  <pre>Another copy</pre>
  <pre>This is the text to be copied</pre>

  <script>
  function copyPreContent() {
    // get the pre element containing the text to be copied
    var preElement = this.nextSibling;

    // get the text to be copied
    var text = preElement.textContent;

    // copy the text to the clipboard using the clipboard API
    navigator.clipboard.writeText(text).then(function() {
      // display a message indicating that the text was copied successfully
      alert('Text copied to clipboard');
    }, function(err) {
      // display an error message if there was a problem copying the text
      console.error('There was an error copying the text: ', err);
    });
  }

  // get all pre elements in the body
  var preElements = document.body.querySelectorAll('pre');

  // add a copy button to just before each pre element
  preElements.forEach(function(preElement) {
    // create a button element
    var button = document.createElement('button');
    button.innerHTML = '<i class="fa fa-clipboard" aria-hidden="true"></i> Copy';
    button.onclick = copyPreContent;

    // add the button just before the pre element
    preElement.parentNode.insertBefore(button, preElement);
  });
  </script>
</body>
</html>



It will output the below:


Output


And that's it! With just a few lines of code, we've created a simple way to copy text to the clipboard using JavaScript. This could be very useful if you are writing a blog post or something like that and you would like your user to copy the content simply by clicking a button.


I hope you found this tutorial helpful. Happy coding!

Related Posts

create-vue-3-slideover-dialog-component-with-tailwind-css
Create Vue 3 SlideOver dialog component with tailwind css 4 minutes read

Imagine you're on a website, and you want to show... Read more

Rezaul H Reza,16 August 2023
drawing-app-using-vue
Drawing App using Vue 8 minutes read

Read more

Rezaul H Reza,28 January 2023
creating-a-chartjs-component-in-alpinejs-and-livewire-a-step-by-step-guide
Creating a Chart.js Component in Alpine.js and Livewire: A Step-by-Step Guide 8 minutes read

"In this tutorial, we will learn how to create a C... Read more

Rezaul H Reza,27 December 2022

Write a comment

Comments (0)