Search code examples
javascripthtmlhtml-tableclipboard

How to copy HTML table to clipboard with js and avoid initial and final blank line in plain text?


The question regarding the copying has certainly been addressed before. I'd like to know if this can be avoided: When pasting the clipboard to a notepad, i. e. I need the plain text, there's always an initial and final blank line in the copied text. Any solution for the snippet below (or any other suggested code) that really only copies the two lines without this initial and final empty line in plain text?

[blank line]    
test1       test2
test3       test4
[blank line]    

let table = document.querySelector('#testTable');
        let button = document.querySelector('#button');

        function selectNode(node) {
            let range = document.createRange();
            range.selectNodeContents(node)
            let select = window.getSelection()
            select.removeAllRanges()
            select.addRange(range)
        }
        button.addEventListener('click', function () {
            selectNode(table);
            document.execCommand('copy')

        })
<style>
        td {
            border: 1px solid black;
        }
    </style>
    
     <table collapsed id='testTable'>
        <tr>
            <td>test1</td>
            <td>&nbsp;</td>
            <td>test2</td>
        </tr>
        <tr>
            <td>test3</td>
            <td>&nbsp;</td>
            <td>test4</td>
        </tr>
    </table>
    <br />
    <button id="button">select</button>


Solution

  • While I don't know the reason, adding a <tbody> element and selecting that one seems to be a possible workaround:

    let table = document.querySelector('#testTable');
    let button = document.querySelector('#button');
    
    function selectNode(node) {
      let range = document.createRange();
      range.selectNodeContents(node)
      let select = window.getSelection()
      select.removeAllRanges()
      select.addRange(range)
    }
    button.addEventListener('click', function() {
      selectNode(table);
      document.execCommand('copy')
    
    })
    <style>
      td {
        border: 1px solid black;
      }
    </style>
    
    <table>
      <tbody id='testTable'>
        <tr>
          <td>test1</td>
          <td>&nbsp;</td>
          <td>test2</td>
        </tr>
        <tr>
          <td>test3</td>
          <td>&nbsp;</td>
          <td>test4</td>
        </tr>
      </tbody>
    </table>
    <br>
    <button id="button">select</button>