Applying Bootstrap "table-striped" after creating table rows dynamically

jquery, twitter-bootstrap

Solution

You should use append to tbody instead of before. The way it is now, the rows are added outside of tbody.

Changing just this line:

$('#table2 > tbody:last').append('<tr><td>' + i +'</td><td>b</td><td>c</td>');

Seems to make your jsFiddle work.

Problem

I'm trying to ensure the Twitter Bootstrap `table-stripped` CSS style is applied to a table whose rows are added dynamically at runtime. For some reason, that I'm trying to get to the bottom of, I can't get this particular style to work so that my new rows are styled with the stripped look. So if I have this HTML with `table-stripped` included: ``` <table class="table table-bordered table-striped table-condensed table-hover" id="table2"> <thead> <tr> <th>Heading A</th> <th>Heading B</th> <th>Heading C</th> </tr> </thead> <tbody></tbody> </table> ``` Then I run this JavaScript code: ``` for (var i = 0; i < 5; i++) { $('#table2 > tbody:last').before('<tr><td>' + i +'</td><td>b</td><td>c</td>'); } ``` I'll get my 5 new rows but they won't have the `table-stripped` style applied. Even if I add the class manually after creating using this it makes no difference. ``` $('#table2').addClass('table-hover'); ``` I've created a jsFiddle sample so you can see this running.

Original source