How to Copy Text To Clipboard using JavaScript


How can we copy some text into our clipboard using JavaScript?

The last two solutions use execCommand(), which is deprecated and may become unusable at any time.

From the Mozilla documentation:

This feature (execCommand()) is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Be aware that this feature may cease to work at any time.

1. Copy text using Clipboard API

In this last method, we’ll be using the new and improved Clipboard API.

const copyToClipboard = (elementId) => {
  const text = document.getElementById(elementId).innerHTML;
  navigator.clipboard
    .writeText(text)
    .then(() => console.log(`"${text}" was copied to clipboard.`))
    .catch((err) => console.error(`Error copying to clipboard: ${err}`));
};

Finally, we can test this last method.

<span id="demo">Copy me!</span>
<button onclick="copyToClipboard('demo')">
  Copy to Clipboard
</button>

2. Copy plain text using execCommand()

In this example, we’re going to perform several steps.

  1. Create a temporary input
  2. Assign the input a value
  3. Append it to the document body
  4. Highlight the contents with select()
  5. Copy the contents with execCommand()
  6. Remove the input from the document body
const copyToClipboard = (elementId) => {
  const temp = document.createElement("input");
  const text = document.getElementById(elementId).innerHTML;
  temp.setAttribute("value", text);
  document.body.appendChild(temp);
  temp.select();
  document.execCommand("copy");
  document.body.removeChild(temp);
};

We can test this method like so:

<span id="demo">Copy me!</span>
<button onclick="copyToClipboard('demo')">
  Copy to Clipboard
</button>

3. Copy formatted text using execCommand()

Copying text into an <input> removes all formatting.

In order to keep the text formatting, we can copy the text into a content editable <div>.

const copyToClipboard = (elementId) => {
  const temp = document.createElement("div");
  temp.setAttribute("contentEditable", true);
  temp.innerHTML = document.getElementById(elementId).innerHTML;
  temp.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  document.body.appendChild(temp);
  temp.focus();
  document.execCommand("copy");
  document.body.removeChild(temp);
};

Let’s do a test.

<span id="demo"><strong>Copy</strong> me!</span>
<button onclick="copyToClipboard('demo')">
  Copy to Clipboard
</button>