Skip to content Skip to sidebar Skip to footer

Alternate Table Row Color Even If Row Is Removed

I want different colors for alternate table rows even when i delete a row in middle. HTML
Row 1

Solution 1:

Try:

<style>tr:nth-of-type(even) {
        background-color:#e3e3e3;
     }

     td:nth-of-type(odd) {
        color:#d04242;
     }
  </style>

Solution 2:

You need to change the class as well

functionupdate_rows() {
    $("tr:even").css("background-color", "#aaa").find('a').removeClass('sam').addClass('sams');
    $("tr:odd").css("background-color", "#eee").find('a').removeClass('sams').addClass('sam');
}

Demo: Fiddle


Use :nth-child if want to support only modern browsers - Demo: Fiddle

tr:nth-child(odd) a {
    background-color:#FF00FF;
}
tr:nth-child(even) a {
    background-color:#0000FF;
}
tr:nth-child(odd) {
    background-color:#aaa;
}
tr:nth-child(even) {
    background-color:#eee;
}

then

$(function () {
    $("a").click(function () {
        $(this).closest('tr').remove();
    });
});

Also note: use $(this).closest('tr').remove() instead of $(this).parent().parent().remove()

Solution 3:

Use CSS3 for the styling:

<tableid="whatever"><tr><td>Row 1</td><td><ahref="#">Delete</a></td></tr><tr><td>Row 2</td><td><ahref="#">Delete</a></td></tr><tr><td>Row 3</td><td><ahref="#">Delete</a></td></tr><tr><td>Row 4</td><td><ahref="#">Delete</a></td></tr><tr><td>Row 5</td><td><ahref="#">Delete</a></td></tr></table><style>#whatevertr {
    background-color: #AAA;
}
#whatevertra {
    background-color:#F0F;
}
#whatevertr:nth-child(odd) {
    background-color: #EEE;
}
#whatevertr:nth-child(odd) a {
    background-color:#00F;
}
</style><script>
$("#whatever a").click(function(){
    $(this).closest("tr").remove();
});
</script>

Now no manual updating, neither for the link classes nor the row backgrounds is needed. See updated demo.

Solution 4:

works perfectly with your tr. the link color doesent change because youre not targeting it with jQuery

Solution 5:

I have updated the fiddle You need the update the class sam and sams

      $("tr:even td a").removeClass("sam").removeClass("sams").addClass("sam");
      $("tr:odd td a").removeClass("sam").removeClass("sams").addClass("sams");

Check on fiddle

Post a Comment for "Alternate Table Row Color Even If Row Is Removed"