How to select an entire HTML table in JS and copy to clipboard

2

I have a simple (but long) HTML table that when selecting and copying ( CTRL + C ) to%

I want to add a button that does this process so you do not have to select this huge table manually and simplify this process. I got the scripts to copy to clipboard, but throwing the content by innerHTML inside a textarea and copying, but goes the source code and not the "result".

How can I give a "select ();" in the table and

asked by anonymous 09.05.2018 / 17:18

1 answer

0

I made tests here and got the next code - JSBIN :

  

NOTE: CSS is in JS BIN, but is irrelevant to the example.

JAVASCRIPT

var Tabela = {
  selecionarTabela: function(el) {
    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);
        }
    } else if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
    try {
      document.execCommand('copy');
      range.blur();
    } catch(error){
      // Exceção aqui
    }
  }
}

var selecionaTabelaBtn = document.querySelector("#selecionar-tabela");
var tabelaDeDados = document.querySelector("#minha-tabela");
// Seleciona a tabela no clique do botão
selecionaTabelaBtn.addEventListener("click", function(){
  Tabela.selecionarTabela(tabelaDeDados);
});

HTML5

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
  <body>
    <!-- Botão de seleção -->
    <button id="selecionar-tabela">Selecionar tabela</button>
    <!-- Tabela a ser selecionada -->
    <table id="minha-tabela">
        <thead>
            <tr>
              <th>Cabeçalho</th>
              <th>Cabeçalho</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Conteúdo</td>
            <td>Conteúdo</td>
          </tr>
          <tr>
            <td>Conteúdo</td>
            <td>Conteúdo</td>
          </tr>
          <tr>
            <td>Conteúdo</td>
            <td>Conteúdo</td>
          </tr>
        </tbody>
    </table>
    <!-- \ Fim da tabela -->
  </body>
</html>
    
09.05.2018 / 18:40