I need to add a class to a tr when it contains td‘s that contain certain values.
Using the answer to this question on SO, I thought I found the solution, but it doesn’t seem to work on rows that contains multiple columns – it only works if there is a single td.
How can I identify the table rows that contain columns with certain values, among other columns? Please note that the columns will not always be in certain order, so it must be a dynamic answer.
<table>
<tr>
<td>Hey!</td>
<td>Other column</td>
<td>Yo!</td>
<td>Other column2</td>
</tr>
</table>
<script type="text/javascript">
$('tr').each(function(){
if (($(this).find('td').text() == 'Hey!' ) && ($(this).find('td').text() == 'Yo!' ))
{
alert('here');
$(this).addClass('disabled');
}
});
</script>
As others have mentioned, use jQuery’s
:contains(text)selector:Something like that.
Edit
Updated my answer to use
lengthinstead of jQuery’ssize()function. Kudos to those who posted evidence to support the notion that usinglengthis faster. After doing some basic research of my own, came across this in the jQuery docs:Given that, plus the test case below, I’m sold. Wonder why
size()even exists? My thought was that it was because some objects returned by jQuery aren’t arrays but only behave like arrays, and that given that usingsize()was preferable. Seems that the later, at least, is not the case.Cheers