Copy to clipboard pure JavaScript

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

by Marcel Ferdinand

HTML

<p id="text_element">Text to copy</p>
<button onclick="copyToClipboard('text_element')">
    Copy to clipboard
</button>
<br><br><br>
<input id="text_element2" type="text" placeholder="Type something and copy"><br><br>
<button onclick="copyToClipboard2('text_element2')">
    Copy to clipboard
</button>
<br/><br/><input type="text" placeholder="Paste here for checking" />

JavaScript

function copyToClipboard(elementId) {

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

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

}

function copyToClipboard2(elementId) {

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

  // Get the text from the element passed into the input
	aux.setAttribute("value", document.getElementById(elementId).value);

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

}