tenub
tenub

Reputation: 3446

Hiding Next Visible Siblings Via If Statement Not Working

I have a search filter function but I'm 99% certain the issue does not lie there.

I first call the search filter then run an if statement to determine if I should hide the row or not.

Imagine I have the following visible table rows after performing a search:

<tr>
  <td class="time">content<td>
</tr>
<tr>
  <td>result</td>
<tr>
</tr>
  <td>result</td>
</tr>
<tr>
  <td class="time">content<td>
</tr>
<tr>
  <td class="time">content<td>
</tr>
<tr>
  <td class="time">content<td>
</tr>

My goal is to hide all td elements which have a time class iff they are proceeded by a row containing a td element with the same class of time. Therefore the if statement should hide the last three rows only in my above example, ie.:

<tr>
  <td class="time">content<td>
</tr>
<tr>
  <td>result</td>
<tr>
</tr>
  <td>result</td>
</tr>

I have tried the following to no avail:

$('td.time').parent().each(function() {
  if($(this).siblings().first().children('td.time').length > 0) {
    $(this).hide();
  }
});

The above works but only if my search returns a single result. If another result exists following a different time row that time row is mistakenly hidden.

Below is what I currently have but it simply hides all time rows even though theoretically it makes sense:

$('td.time').parent().each(function() {
  if($(this).next(':visible').children('.time')) {
    $(this).hide();
  }
});

My only explanation is that with .next() it's only looking at the next td.time parent rather than the next of all visible table rows.

Upvotes: 1

Views: 204

Answers (2)

Adil
Adil

Reputation: 148140

Try using nextAll() to parent tr and you probably do not need to use each over here to hide all next tr having td with class time .

Live Demo

$(this).closest('tr').nextAll('tr:has(td.time)').hide();

Upvotes: 1

gpasci
gpasci

Reputation: 1440

It's not very elegant but try this

$(".time").each(function() {
    if ($(this).parent("tr").next("tr").find(".time").length > 0) {
        $(this).parent("tr").hide();
    }
});

Upvotes: 0

Related Questions