Add Class Attribute to Markdown Table

Earlier this week I faced the problem converting Markdown tables to HTML, unfortunately there was no way to specify custom class attribute in resulting HTML.

And that’s was quite critical for me, since my current theme is Twitter Bootstrap based and I have no other choice, but explicitly specify the class names to make styles works.

Applying styles globally, i.e. to every table element, wasn’t an options, because table element is used in some others plugins, for example for sharing code snippets.

After some research, I come up with a simple and straight forward solution :)

I placed tables in between of two HTML placeholders and used jQuery to fine tune those and only those as needed.

Beginning of Table

1
<div class="tables-start"></div>

Table

1
2
3
4
5
id | name
---|---
1  | London
2  | Paris
3  | Berlin

End of Table

1
<div class="tables-end"></div>

jQuery: Fine tune tables by adding the classes

1
2
3
4
5
<script type="text/javascript">
(function() {
    $('div.tables-begin').nextUntil('div.tables-end', 'table').addClass('table table-bordered');
})();
</script>

Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.

Result

Beautiful looking tables in both, Markdown and HTML :)

Other Options

  • Write tables as inline HTML
  • Switch to another markdown processor, e.g. Kramdown

Comments