How to copy text from a div to clipboard

I tried the solution proposed above. But it was not cross-browser enough. I really needed ie11 to work.
After trying I got to:

    <html>
        <body>
            <div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
            <script>
                function copyDivToClipboard() {
                    var range = document.createRange();
                    range.selectNode(document.getElementById("a"));
                    window.getSelection().removeAllRanges(); // clear current selection
                    window.getSelection().addRange(range); // to select text
                    document.execCommand("copy");
                    window.getSelection().removeAllRanges();// to deselect
                }
            </script>
        </body>
    </html>

Tested with firefox 64, Chrome 71, Opera 57, ie11(11.472.17134.0), edge( EdgeHTML 17.17134)

Update March 27th, 2019.

For some reason document.createRange() didn’t work before with ie11. But now properly returns a Range object. So is better to use that, rather than document.getSelection().getRangeAt(0).

Leave a Comment