Replace certain tag with another when copying to clipboard

Viewed 38

I'm trying to copy a table from the webpage to either Word document or email, but everything in <textarea> just cannot display correctly after pasting.

I found a couple ways to replace the <textarea> tag with <span>, but because I don't want to affect the editability of the original table, I have to manipulate the clone of the table Element.
The question is, how do I send this cloned & modified table element to the clipboard without affecting the actual DOM?

copy method learned from Copy the HTML table to clipboard in reactjs

copyTable = () =>{
    const elTable = document.getElementById('my_table').cloneNode(true);
    var textareas = elTable.getElementsByTagName('textarea');
    for(let txtarea of textareas){
      var span = document.createElement('span');
      span.innerText = txtarea.defaultValue;
      txtarea.parentNode.appendChild(span);
      txtarea.parentNode.removeChild(txtarea);
    }
    
    var range, sel;
    if(document.createRange && window.getSelection){
      range = document.createRange();
      sel = window.getSelection();
      sel.removeAllRanges();
      
      try{
        range.selectNodeContents(elTable);
        console.log("range:",range);
        sel.addRange(range);
      }catch(e){
        range.selectNode(elTable);
        sel.addRange(range);
      }
      
      document.execCommand('copy');
    }
    sel.removeAllRanges();
    
    console.log("copied");
  }

If I don't make elTable a clone, then the swap works and so does the copy, but it also changes the <textarea> to <span> on the actual DOM, which is something I don't want.
If I use document.getElementById('my_table').cloneNode(true);, then the copy doesn't work at all for some reason..

Is there a way to send my cloned/modified table element to the clipboard? Any help is appreciated!

1 Answers

The issue is that there is nothing selected on the cloned node, only on the original.

To do this you need to:

  • Clone the table
  • Modify the original
  • Write modified original to clipboard
  • Replace original with clone
Related