Using the table-striped bootstrap after dynamically creating table rows

I am trying to provide Twitter Bootstrap table-stripped The CSS style is applied to a table whose rows are dynamically added at runtime. For some reason, that I'm trying to figure this out, I can't get this particular style to work so that my new lines are styled with intelligence.

So, if I have this HTML with table-stripped enabled:

 <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 will get 5 new rows, but they will not have table-stripped style.

Even if I add the class manually after creating it, it does not matter.

 $('#table2').addClass('table-hover'); 

I created a jsFiddle sample so you can see how this works.

+6
source share
2 answers

You should use append for tbody , not before. So, as of now, lines are added outside tbody .

Change this line only:

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

It seems your jsFiddle is working.

+7
source

Change to .append() to <tbody> , and also fix the missing closure </tr> .

Demo

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

Using .before() , you insert lines in front of the body, which is why the style is not applied because the Bootstrap style targets lines that are children of the body.

+3
source

Source: https://habr.com/ru/post/949532/


All Articles