Copy to clipboard pure JavaScript

Copy text from <p> element into clipboard using only JavaScript

by John Doe

HTML

<p id="text_element">Copy thi</p>

<button onclick="copyToClipboard()">
    Copy to clipboard
</button>
<br/><br/><input type="text" placeholder="Paste here for checking" />

JavaScript

function copyToClipboard() {

  // Create an auxiliary hidden input
  var aux = document.createElement("input");
	var elementId = 'text_element';
  // Get the text from the element passed into the input
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append the aux input to the body
  document.body.appendChild(aux);

  // Highlight the content
  aux.select();

  // Execute the copy command
  document.execCommand("copy");

  // Remove the input from the body
  document.body.removeChild(aux);

}