Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 433
Bern Avatar asked Jul 16 '13 08:07

Bern


People also ask

Which of the following bootstrap table is used to color rows or data of the table?

Contextual classes can be used to color the whole table ( <table> ), the table rows ( <tr> ) or table cells ( <td> ).

What is table-striped?

.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.

How do I change the background color of a table in bootstrap?

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.


2 Answers

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.

like image 143
Naor Biton Avatar answered Oct 23 '22 21:10

Naor Biton


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.

like image 4
MrCode Avatar answered Oct 23 '22 21:10

MrCode