'how to add class on table using javascript in tinymce?

I have some problem to add class on table. I wanna this code

<table></table>

become this code by click a button in tinymce.

<table class="try-class"></table>

I have add button, and still cannot solve how to add code on tinymce table plugin. thank you... :)



Solution 1:[1]

Look at the style_formats option for the TinyMCE configuration file:

https://www.tinymce.com/docs/configure/content-formatting/#style_formats

You can target a certain tag as being relevant for the style you wish to add. For example:

style_formats: [
    {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
    {title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
    {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}    
]

...would allow you to add a class tablerow1 to a <tr> tag within the editor.

Solution 2:[2]

I had hoped style_formats would have worked, but it did nothing for me. This is finally what I used to add custom classes to my tables:

table_default_styles: {},
table_default_attributes: { class: 'table table-bordered table-striped' },

This first removes all of the automatic styles tinymce adds (like width). Then it overrides tinymce's default attributes with a class attribute where I specify the classes I want.

In my case I'm using Bootstrap, so I want tables to have Bootstrap classes.

Solution 3:[3]

I use jQuery on the page to target the table:

<script>
    $table = $('table').addClass('table table-condensed table-responsive');
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mr Lister
Solution 2 Chris
Solution 3 NMeneses