简体   繁体   中英

Copy HTML elements to clipboard using javascript code

I am not trying to copy text to the clipboard. I have an array of html elements (contiguous divs) representing cells in a grid. They are selected using jquery and I am trying to find out if there is a way to copy them onto the clipboard like a table that can be pasted elsewhere, like in MS excel for example.

Every resource on the internet only talks about copying text, not html elements.

You can stringify a DOM element node or a tree using [selector].outerHTML . The most direct approach would be to show a prompt that contains the HTML element text, which you can then copy off of:

var selectedText = [selector].outerHTML;
function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", selectedText);
}
// Using http://stackoverflow.com/a/6055620/3157745

As for the export into Excel, there's no way you can simply copy and paste a string of any sorts and drop that into a table. However, what you can do is parse the HTML element, format that into a CSV, which then can be opened with Excel. As for how that might be achieved, we'd need to see the structure of your HTML.


Update

If possible, try using jquery DataTables . It can export your Table as XLSX, CSV, PDF and all you would need to do is initialize your table with:

$(document).ready(function() {
    $('#example').DataTable()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM