Copy by Javascript and HTML Tag

Asked

Viewed 209 times

0

I have four HTML files and within them have several tables <table>.

I am trying to put at the end of each of these files a code to copy only the tables, so that later I can paste in excel and go organizing. I’m not getting the tag copy.

I want to make a fifth file, which copies all tables to paste in excel.

<button onclick="copy()">Copiar</button><br>


<script type="text/javascript">
    function copy(){
        var text = document.getElementsByTagName("table");
        var range = document.createRange();

        range.selectNode(table);
        window.getSelection().addRange(range);
        document.execCommand('copy');

    }
</script>

1 answer

1

Dante, you’re setting the variable to "text" and calling her on selectNode as "table". In addition, the method getelementsbytagname will return an Htmlcollection, so you will need to iterate over this collection to select each table in the selectNode.

Unfortunately it is not possible to copy the contents of all tables at once. You will need to copy item by item. An alternative to this is to add the items in a variable and at the end copy the variable to the Clipboard.

Follow the example of the code:

 
function copy() {

    var tables = document.getElementsByTagName("table");
    var range = document.createRange(); 
    var content = "";

    for (let table of tables) {  

        range.selectNode(table);

        window.getSelection().removeAllRanges();        
        window.getSelection().addRange(range); 
        
        document.execCommand('copy');
        content += window.getSelection().toString();
    }  
    
    copyToClipboard(content);
}


function copyToClipboard(text) {
  
    var textArea = document.createElement("textarea"); 
    textArea.value = text;  
    document.body.appendChild(textArea);   

    textArea.select();

    document.execCommand('copy');  
    document.body.removeChild(textArea); 
}  

  • Thank you Devgirl

Browser other questions tagged

You are not signed in. Login or sign up in order to post.