gainsky gainsky - 3 months ago 7
Javascript Question

How to add a class to tr, if one of its td's have some content.

How to add a class to tr, if one of its td's have content. Here is my code.

HTML

<table>
<tr>
<td>Some content</td>
<td>Some content</td>
<td></td>
<td>Some content</td>
<td>Some content</td>
<td class="last"></td>
</tr>
<tr>
<td>Some content</td>
<td>Some content</td>
<td>Some content</td>
<td>Some content</td>
<td>Some content</td>
<td class="last">Some content</td>
</tr>
</table>


Jquery

$('tr').each(function(){
if($('td.last').length > 0 {
$(this).addClass('someclass');
}
});


https://jsfiddle.net/odpb3tg3/

Answer

Try this with :not and :empty and closest() in a single line,

$('td.last:not(:empty)').closest('tr').addClass('someclass');

$('td.last:not(:empty)').closest('tr').addClass('someclass')
.someclass{color:red}
.someclass .last{color:blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Some content</td>
    <td>Some content</td>
    <td></td>
    <td>Some content</td>
    <td>Some content</td>
    <td class="last"></td>
  </tr>
  <tr>
    <td>Some content</td>
    <td>Some content</td>
    <td>Some content</td>
    <td>Some content</td>
    <td>Some content</td>
    <td class="last">Some content</td>
  </tr>
</table>

Comments