Skip to content

Instantly share code, notes, and snippets.

@styfle
Created September 19, 2016 20:44
Show Gist options
  • Save styfle/c4bba2d29e6cb9b585de72207c006af7 to your computer and use it in GitHub Desktop.
Save styfle/c4bba2d29e6cb9b585de72207c006af7 to your computer and use it in GitHub Desktop.
Convert an HTML Table in the DOM to a Markdown Table as a string
function toMarkdown(doc) {
let s = '| ';
let thead = doc.querySelector('thead');
let headcells = thead.querySelectorAll('td');
for (let i = 0; i < headcells.length; i++) {
let cell = headcells[i];
s += cell.textContent.trim() + ' | ';
}
s += '\n'
for (let i = 0; i < headcells.length; i++) {
s += '|---------'
}
s += '|\n'
let tbody = doc.querySelector('tbody');
let trs = tbody.querySelectorAll('tr');
for (let i = 0; i < trs.length; i++) {
s += '| '
let tr = trs.item(i);
let tds = tr.querySelectorAll('td');
for (let j = 0; j < tds.length; j++) {
let td = tds.item(j);
s += td.textContent.trim() + ' | ';
}
s += '\n';
}
return s;
}
// Usage Example: only one table on the page
var md = toMarkdown(document);
console.log(md);
// Usage Example: specify table container
var el = querySelector('#table-container');
var md = toMarkdown(el);
console.log(md);
@Fechin
Copy link

Fechin commented Jan 25, 2019

nice!

@Tilesto
Copy link

Tilesto commented Mar 25, 2021

Thanks a lot!

@Sejmou
Copy link

Sejmou commented Apr 2, 2022

Hi, thanks for your code. Just wanted to add that header rows (<tr>) usually contain the columns as <th> elements, not <td>. See also the table example (HTML and visual output ) of the example in the HTML table tutorial on MDN.

With the table I had to convert, I then had the issue that the header remained empty, as the <th> elements were not selected. I had to change line 5 to

let headcells = thead.querySelectorAll('td, th');

Sometimes (also in the examples linked above), the <thead> element is missing and one would have to potentially consider that case in the code as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment