javascript - how to ensure that each time a css class name changes from the previous, it is applied a specific style -


i have table structure shown below, , want make sure each time switches class 'odd' 'even' or 'even' 'odd', s inside row of new class applied style. in example, first 'even' row after 7 odd rows have s greater top padding rest, , then, first 'odd' row after (7 rows down) have greater top padding well.

i can use either css (preferred) or javascript / jquery accomplish this. how make happen? note not have ability generate initial table structure in different markup shown below.

enter image description here


table generating function (only concerned structure of 'newtable'):

  $('.table').each(function() {     var table = $(this); // cache table object     var head = table.find('thead th');     var rows = table.find('tbody tr').clone();      var newtable = $(       '<table class="table mobile">' +       '  <tbody>' +       '  </tbody>' +       '</table>'     );      // cache tbody we'll adding data     var newtable_tbody = newtable.find('tbody');      rows.each(function(i) {       var cols = $(this).find('td');       var classname = % 2 ? 'even' : 'odd';        cols.each(function(k) {         var new_tr = $('<tr class="' + classname + '"></tr>').appendto(newtable_tbody);         var headel = head.clone().get(k);         new_tr.append(headel);         new_tr.append($(this));         var isempty = $(headel).hasclass('empty'); //check table columns being used headers, make sure span 2 columns on mobile regular table data isn't wide column header. note assumes mobile `.table`s ever 2 columns         if (isempty){           $(this).attr('colspan',2);         }       });     });      $(this).after(newtable);   } 

you can achieve using css' + next sibling selector.

.odd {    color: red;  }  .even{    color: blue;  }    tr.odd + tr.even td {    padding-top: 20px;  }    tr.even + tr.odd td {    padding-top: 20px;  }
<table>    <tr class="even">      <td>sample row 01</td>    </tr>    <tr class="even">      <td>sample row 02</td>    </tr>    <tr class="even">      <td>sample row 03</td>    </tr>    <tr class="odd">      <td>sample row 04</td>    </tr>    <tr class="odd">      <td>sample row 05</td>    </tr>    <tr class="odd">      <td>sample row 06</td>    </tr>    <tr class="even">      <td>sample row 07</td>    </tr>    <tr class="even">      <td>sample row 08</td>    </tr>    <tr class="odd">      <td>sample row 09</td>    </tr>    <tr class="even">      <td>sample row 10</td>    </tr>  </table>


Comments