Copy to clipboard pure JavaScript

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

by John Doe

HTML

<p id="text_element">lorm</p>

<button id="copytc">
    Copy to clipboard
</button>
<br/><br/><input type="text" placeholder="Paste here for checking" />

JavaScript

$('.copytc').click(function() {

  // Create an auxiliary hidden input
  var aux = document.createElement("input");
  var elementId = 'copytc';

  // 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);

});