Gaspa79 Gaspa79 - 3 months ago 11
CSS Question

Remove a table row but keep the CSS alternate rows format

So I have a table that has an alternating format for rows (let's say grey and white). I'm deleting a row with the tr.remove() jquery function, and of course the css of the rows over/under it will not change, and they will keep their odd/even styles. Basically:

Before Deletion After Deletion

grey grey
white white
grey white
white grey
grey


Is there any way to quickly force the table to "refresh" the styles? Or do I have to apply them manually using jquery?

Thanks a lot!

Answer

So do the styling with CSS instead of using odd/even classes/ hardcoding values.

document.querySelector("tbody").addEventListener("click", function(e) {
    var td = e.target,
        tr = td.parentNode;
        tr.parentNode.removeChild(tr);
    
});
    tr:nth-child(even) {
      background-color: #FFF;
    }
    
    tr:nth-child(odd) {
      background-color: #CCC;
    }
<table>
  <tbody>
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
    <tr><td>3</td></tr>
    <tr><td>4</td></tr>
    <tr><td>5</td></tr>
    <tr><td>6</td></tr>
  </tbody>
</table>

Comments