Copy Text to Clipboard

How to copy text from an HTML element (div, p, span) to the clipboard

 

 

Add the following javascript code to your page:

<script>
function CopyToClipboard(id)
{
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
</script>

Copy Code to Clipboard

 

The function copies the visible text of the element to the clipboard.
This works as if you had selected the text and copied it with ctrl+c.
Use the parameter "id" to select the element you want to copy.

 

Samples:

<p id="sample">Hello World</p>

The following link copies the text within the specified element (in this sample the paragraph with id="sample") to the clipboard:

<a href="#" onclick="CopyToClipboard('sample');return false;">Copy Text</a>

You can also copy the text from other elements, like e.g. a <span>:

<span id="sample">Hello World</span>

or a <div>:

<div id="sample">Hello World</div>

Disclaimer: The information on this page is provided "as is" without warranty of any kind. Further, Arclab Software does not warrant, guarantee, or make any representations regarding the use, or the results of use, in terms of correctness, accuracy, reliability, currentness, or otherwise. See: License Agreement