Copy to Clipboard using JavaScript.

Below is the easiest way to use JavaScript to copy element to Clipboard.



<table id="tableId">

    <thead>

        <tr><th>Heading</th><th>Heading</th></tr>

    </thead>

    <tbody>

        <tr><td>cell</td><td>cell2</td></tr>

    </tbody>

</table>



<input type="button" value="select table"

   onclick="copyElementContents( document.getElementById('tableId') );">


<script>

    function copyElementContents() {

            var el = $('*[id*=pbt]')[0]; // element to be copied to clipborad

            var body = document.body, range, sel;

            if (document.createRange && window.getSelection) {

                range = document.createRange();

                sel = window.getSelection();

                sel.removeAllRanges();

                try {

                    range.selectNodeContents(el);

                    sel.addRange(range);

                } catch (e) {

                    range.selectNode(el);

                    sel.addRange(range);

                }

                document.execCommand("copy");

                sel.removeAllRanges();

            } else if (body.createTextRange) {

                range = body.createTextRange();

                range.moveToElementText(el);

                range.select();

                range.execCommand("copy");

               

            }

        }

</script>
Enjoy Coding .

If have any doubt please comment.

Thanks.