Select contents of element and its children and copy to clipboard (Javascript)

Sometimes it's helpful, particularly with a long element, to provide a button which automatically selects the entire content of a given element (including any children) and copies to clipboard

This snippet provides a function for just that purpose

Details

  • Language: Javascript

Snippet

function CopyToClipboard(containerid) {
     window.getSelection().selectAllChildren(document.getElementById(containerid));
     document.execCommand("copy");
}

Usage Example

<button onclick="CopyToClipboard('longblock');">Copy to Clipboard</button>
<div id="longblock">
    <div id="intro">
        <h3>Intro</h3>
        <p>Blah blah blah</p>
    </div>
    <div id="body">
        <h3>Blah</h3>
        <p>Blah blah</p>
    </div>
</div>