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.
Contextual classes can be used to color the whole table ( <table> ), the table rows ( <tr> ) or table cells ( <td> ).
.table-striped. Adds zebra-striping to any table row within <tbody> (not available in IE8) Try it. .table-bordered. Adds border on all sides of the table and cells.
Using pre-defined classes, we can change the color of table cells and table rows. In order to change the color of the table row, we need to specify in <tr> tag with the required class & for changing the color of the table row then specify it inside <td> tag with the required class.
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.
Change to .append()
to the <tbody>
and also fix your missing closing </tr>
.
Demo
$('#table2 > tbody').append('<tr><td>' + i +'</td><td>b</td><td>c</td></tr>');
By using .before()
you were inserting the rows before the tbody which caused the style not to be applied because the Bootstrap style targets rows that are children of the tbody.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With