SNos
SNos

Reputation: 3470

Find and remove style attribute on click

I am trying to remove the style attribute from a singular tr tag in a table when the corresponding tag is clicked. Have been trying some code but cannot find the solution.

here the fiddle: http://jsfiddle.net/q2nb08t6/12/ jQuery:

$(".tr_table").click(function(){

$(".tg_table").removeAttr('style');
//$(".tg_table").parent().find("tg_table").removeAttr('style');    
//$(".tg_table").parent().removeAttr('style');
//$(".tg_table").each().removeAttr('style');
});

Upvotes: 0

Views: 917

Answers (2)

harunurhan
harunurhan

Reputation: 1604

As far as I know also stated here, you can't remove style that is inherited from parent unless you overwrite it. The best solution here, find a default style and when row clicked set this style which will remove the parent's style.

Code here, $(this) refers the clicked element.

$(".tr_table").click(function(){
    $(this).attr('style','background-color: rgba(255,255,255,0.5) !important;color:white !important;');
});

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30567

  1. Change your approach. Apply that style on the tr level instead of the table level
  2. Use removeClass() to remove the class when clicked. Or, you can use toggleClass() to toggle the class when clicked.

$(".tr_table").click(function() {
  $(this).toggleClass('tr_table');
});
.tg_table {
  width: 100%
}
.tr_table {
  cursor: pointer;
}
tr.tr_table {
  background-color: rgba(255, 0, 0, 0.5) !important;
  color: white !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<table class="tg_table" border="1" style="">
  <tr class="tr_table">
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr class="tr_table">
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
  <tr class="tr_table">
    <td>Neil</td>
    <td>Mark</td>
    <td>30</td>
  </tr>
  <tr class="tr_table">
    <td>Mike</td>
    <td>Ford</td>
    <td>98</td>
  </tr>
</table>

Update

Unfortunately I cannot change the approach as the table is generated by php script

In that case, you can change the tr styles with css()

$(".tr_table").click(function() {
  $(this).css('background', 'white');
  $(this).css('color', 'black');
});
.tg_table {
  width: 100%
}
.tr_table {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table class="tg_table" border="1" style="background-color: rgba(255,0,0,0.5) !important;color:white !important;">
  <tr class="tr_table">
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr class="tr_table">
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
    <tr class="tr_table">
    <td>Neil</td>
    <td>Mark</td> 
    <td>30</td>
  </tr>
    <tr class="tr_table">
    <td>Mike</td>
    <td>Ford</td> 
    <td>98</td>
  </tr>
</table>

Upvotes: 1

Related Questions