gabebt gabebt - 4 months ago 8
jQuery Question

Selecting multiple table classes in jQuery loop

I have a table that uses jQuery & moment.js to get the time from a column, check if the time is greater than X minutes from now, and if so, highlight the cell.

For example: https://jsfiddle.net/kjscq4ra/

<table id="myTable">
<tr>
<th>Number</th>
<th>Name</th>
<th>Time</th>
</tr>
<tr>
<td>123</td>
<td class="person">Jack "Smith"</td>
<td class="time">8/03/2016 8:35:00 AM</td>
</tr>
<tr>
<td>246</td>
<td class="person">John "A" Doe</td>
<td class="time">8/03/2016 7:05:30 AM</td>
</tr>
<tr>
<td>369</td>
<td class="person">Jane</td>
<td class="time">8/03/2016 7:15:25 AM</td>
</tr>
</table>


$('#myTable td.time').each(function() {
var cellText = $(this).text();
var a = moment();
var b = moment(cellText, "MM/DD/YYYY hh:mm:ss");
var difference = a.diff(b, 'minutes');
if (difference >= 60) {
$(this).css('background-color', '#FFBABA');
};
});


I'd like to add a condition to my
if
statement to also check the "person" column for certain text before highlighting the "time" column. For example, only highlight the "time" column if the "person"
td
contains an apostrophe in the name:

$("#myTable td.person:contains('\"\')")


Could anyone point me in the right direction?

Answer

See jQuery's prev function:

$('#myTable td.time').each(function() {
  var $timeCell = $(this),
    cellText = $timeCell.text(),
    personText = $timeCell.prev('.person').text(),
    a = moment(),
    b = moment(cellText, "MM/DD/YYYY hh:mm:ss"),
    difference = a.diff(b, 'minutes');

  if (difference >= 60 && personText.indexOf('"') > -1) {
    $timeCell.css('background-color', '#FFBABA');
  }
});

https://jsfiddle.net/kjscq4ra/4/

Comments