In the browser context, the document node has execCommand method, which has the following syntax:

  document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

This method can do many magical things, one of which is copying text to the clipboard.

For this, simply use Copy in place of aCommandName in the syntax mentioned above, like this:

  // myInputElement is some <input type="text"> element

// Select the value/contents of the element;

// Copy it to clipboard

But wait, there's a little thing to know here.

For copying the text, you need to select it. But select doesn't works for every HTML element. I specifically used the input element here because it is one of the elements which supports select() (since it becomes an editable region easily and the execCommand() affects the editable region only and blah blah boring stuff).

Long story short, for the easiest use-case, you need an input type="text"> element, and you can then select it and execute the copy command on it.

But what if you wanted to select and copy text from some other element, say some <h1> tag? Easy:

  1. Get the text that you want to copy in a variable, using innerText() on the element
  2. Create a temporary <input type="text"> element
  3. Set the value of this temporary input element to whatever text you want to copy
  4. Append the temporary input element to document.body using appendChild()
  5. Use select() method to select the (text of) the appended input element
  6. Use document.execCommand("Copy"); [Notice the capital C in Copy]
  7. Now our work is done, but make sure to not leave that temporary element in the document, remove it using removeChild()
  8. Congrats, the text has been copied to clipboard now, paste it wherever you want to see if it worked for you

Here is the easy code for the above, wrapped in a function for you:

[Note, parameter element is the reference to the target HTML element (whose text you want to copy), which you may get by using document.querySelector() or document.getElementById() and so on..]

  function copyText(element) {

    var textToCopy = element.innerText;

    var myTemporaryInputElement = document.createElement("input");
    myTemporaryInputElement.type = "text";
    myTemporaryInputElement.value = textToCopy;




And finally a working pen showing the same:

Document.execCommand() on MDN
Me on Twitter
Me on LinkedIn