Copy by Javascript and HTML tags

0

I have four HTML files and inside of them have multiple tables <table> .

I'm trying to put at the end of each of these files a code to just copy the tables, so that later I can paste in excel and go organizing. I am not able to copy it by tag.

I want to make a fifth file, which copies all the tables to paste into 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>
    
asked by anonymous 10.09.2018 / 15:17

1 answer

1

Dante, you are setting the variable to " text " and calling it in selectNode as " table ". In addition, the getElementsByTagName method 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 to a variable and at the end, copy the variable to the clipboard.

Here is the code example:

 
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); 
}  
    
10.09.2018 / 20:50