Reputation: 175
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/
Upvotes: 0
Views: 49
Reputation: 1443
Change your code
$('tr').each(function(){
if($('td.last').length > 0 {
$(this).addClass('someclass');
}
});
To
$('tr').each(function() {
if ($(this).find("td.last").text().length > 0) {
$(this).addClass('someclass');
}
});
You need to use $(this).find("td.last").text()
instead of $('td.last')
Upvotes: 1
Reputation: 115212
Use combination of :has()
, :not()
and :empty
psedudo class selectors.
$('tr:has(td.last:not(:empty))').addClass('someclass');
$('tr:has(td.last:not(:empty))').addClass('someclass');
.someclass {
color:red
}
<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>
Upvotes: 2
Reputation: 40639
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>
Upvotes: 1
Reputation: 67187
You can do it effectively by using .filter()
,
$('tr').filter(function(){
return $('td.last', this).text().length > 0;
}).addClass("SomeClass");
And you have to traverse the tds
based on this object.
Upvotes: 3