This post will discuss how to copy some text from DOM to the clipboard using JavaScript.

1. Using Document.execCommand('copy') method

To copy a text from an input element or a textarea on DOM, you can use the document.execCommand method. The idea is to create a fully transparent textarea and attach it to the document’s body. Then set its content with the text you want to be copied to the clipboard. Finally, call document.execCommand('copy') after programmatically selecting the textarea contents and then remove the textarea from the document.

Here’s a working example:

JS


HTML



Edit in JSFiddle

 
Note that the clipboard access is synchronous (i.e., the browser blocks the page), leading to a poor user experience. Therefore, its use is discouraged, and it may be removed in the future.

Also, note that you can only call document.execCommand('copy') from an event handler such as onclick due to security restrictions.

2. Using Clipboard API

Since the execCommand-based copy and paste are obsolete due to its synchronous nature, the new Promise-based Async Clipboard API should be used instead, which doesn’t block the page due to its well-defined permissions model.

You can call the writeText() method to copy text to the clipboard, which uses an ES6 Promise, which will be resolved or rejected depending upon whether the copying is a success or failure.

JS


HTML



Edit in JSFiddle

 
You can also write an async function and await the return of writeText():

JS


HTML



Edit in JSFiddle

3. Using Clipboard API Polyfill

Alternatively, you can use the clipboard-polyfill library, a polyfill for the modern asynchronous clipboard API. To copy, simply call its clipboard.writeText() method.

JS


HTML



Edit in JSFiddle

That’s all about copying text to the clipboard with JavaScript.