title: export to CSV with Javascript
body: <p>I have two functions</p>
  
  <ol>
  <li>Exports HTML Table</li>
  <li>Download CSV file</li>
  </ol>
  
  <p>Unfortunately my file is downloading as "Undefined" with no .csv file type.</p>
  
  <p>The format seems to be fine, since the file can be opened with any text editor and can be seen to have all table data with a comma as a delimitter. Which makes it easy for Excel to take in the file and seperate each column and row.</p>
  
  <p>But I need the file to download with the .csv file extension.</p>
  
  <p>Here are my two functions: </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function exportTableToCSV(html, filename) {
      var csv = [];
      var rows = document.querySelectorAll("table tr");
  
      for(var i = 0; i &lt; rows.length; i++){
          var row = [], cols = rows[i].querySelectorAll("td, th");
          for(var j = 0; j &lt; cols.length; j++){
              row.push(cols[j].innerText);
          }
          csv.push(row.join(","));
      }
  
      // download csv file
      downloadCSV(csv.join("\n"), filename);
  }
  
  function downloadCSV(csv, filename) {
          var csvFile;
   var downloadLink;
  
   csvFile = new Blob([csv], {type:"text/csv"});
   downloadLink = document.createElement("a");
   downloadLink.download = filename;
   downloadLink.href = window.URL.createObjectURL(csvFile);
   downloadLink.style.display = "none";
   document.body.appendChild(downloadLink);
   downloadLink.click();
  }
  
  exportTableToCSV('', 'test.csv');</code></pre>
  </div>
  </div>
  </p>
  
  <p>I believe the issue lies with 'function downloadCSV'. Any help or links to some current working examples are highly appreciated.  </p>