Select contents of element and its children and copy to clipboard



Published: 2019-10-13 12:10:17 +0000
Categories: Javascript,

Language

Javascript

Description

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

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>

Keywords

js, clipboard, copy, select,

Latest Posts


Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, yr4pnhounvdybotb.onion and snippets.6zdgh5a5e6zpchdz.onion