gabebt gabebt - 1 year ago 60
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:

<table id="myTable">
<td class="person">Jack "Smith"</td>
<td class="time">8/03/2016 8:35:00 AM</td>
<td class="person">John "A" Doe</td>
<td class="time">8/03/2016 7:05:30 AM</td>
<td class="person">Jane</td>
<td class="time">8/03/2016 7:15:25 AM</td>

$('#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
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"
contains an apostrophe in the name:

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

Could anyone point me in the right direction?

Answer Source

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');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download