HTML Table to CSV

by Raul Bojalil

HTML

<table>
<thead>
  <tr>
    <th>ID</th>
     <th>Username</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>1</td>
    <td>uno</td>
  </tr>
  <tr>
    <td>2</td>
    <td>dos</td>
  </tr>
  <tr>
    <td>3</td>
    <td>tres</td>
  </tr>
</tbody>
</table>

JavaScript

var tableToCsv = function(tableElement)
{
	  var csv = [];
    
    tableElement.find("thead tr").each(function(){
    	  var index = 0;
    	  $(this).find("th").each(function(){
             if(index > 0) csv.push(",");
             csv.push($(this).html());
             index++;
        });
        csv.push("\n");
    });
    
    tableElement.find("tbody tr").each(function(){
        var index = 0;
    	  $(this).find("td").each(function(){
             if(index > 0) csv.push(",");
             csv.push($(this).html());
             index++;
        });
        csv.push("\n");
    });
    
    return csv.join("");
}

console.log(tableToCsv($("table")));