As we know a CSV file is a Comma Separated Values file that contains plain texts as a list of data. So, we gonna create a function that will take all data from an HTML table, separate all the td (table data/cell) or th (table header) with a comma and for every tr (table row) we’ll use a line break (newline).
We’ll use BLOB to convert those raw data into a file-like object. Then we’ll create an URL for that object using URL.createObjectURL() method. Next, we’ll create an “a” tag element, we put the BLOB object’s URL in it’s href attribute and give a file name in the download attribute. Finally, we’ll insert it in the dom, trigger its click event and remove it from the dom.
Now we’ve got a working function that accepts an HTML table and a name for the CSV file, which will start downloading the CSV file.