1

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.

rex
  • 2,785
  • 5
  • 31
  • 56
  • You mean *contiguous ? – Ivan Santiago May 06 '16 at 15:38
  • yep - thanks for correction – rex May 06 '16 at 15:40
  • When you copy something, its usually text. The difference is that you can 'encode' the text and then paste it on a program that 'decodes' that text to in a certain way. In excel, if you paste a text with tabs and new lines, the tabs will go to next column and new line will go to next row – juvian May 06 '16 at 15:44
  • @juvian thanks - that makes sense and sounds like the easiest solution for now. Formatting isn't that important I suppose. – rex May 09 '16 at 08:04
  • @armensg90 that is the easiest way, but if you really need to keep formatting you should look into xml: http://stackoverflow.com/questions/1177365/importing-html-table-into-excel-via-clipboard – juvian May 09 '16 at 14:53
  • I've managed to build a html table element from the divs- now i just need to figure out how to put the variable on the clipboard! – rex May 09 '16 at 15:00

1 Answers1

0

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()
});
Xenyal
  • 1,834
  • 2
  • 21
  • 43
  • yeah i dont mind processing it into a csv string or something. Ill post the strucutre of my HTML – rex May 06 '16 at 15:58