Trey Hunner
Trey Hunner

Reputation: 11814

Select every visible last child in jQuery

I would like to get the last visible td in each tr in a table.

This does not work because it attempts to select the last child if it is visible:

var last_visible_cells = $(table).find("tr td:visible:last-child");

So far the simplest method I've thought of is to use a .each to loop through the tr elements and append each of the last visible tds to a new selector list.

Is there a simpler way? Does anything like this exist?

var last_visible_cells = $(table).find("tr").lastMatching("td:visible");

Upvotes: 10

Views: 6669

Answers (4)

Amin Eshaq
Amin Eshaq

Reputation: 4024

to get every last visible them you can do something like

$('table tr').each(function(){
    console.log($(this).find('td:visible:last'))
})

Upvotes: 2

ChessWhiz
ChessWhiz

Reputation: 4702

Based on the answer from Mathletics, but using nextUntil(). This finds each visible tag that doesn't have a following visible tag.

$('table tr').children('td').filter(function() { 
  return $(this).is(':visible') && $(this).nextUntil(':visible').length === 0; 
})

Upvotes: 0

David Rodrigues
David Rodrigues

Reputation: 12532

You can do it:

$('table tr').find('td:visible:last').addClass('last-visible');

See a full example (jQuery 1.2+ compatible)

Upvotes: 19

Evan Davis
Evan Davis

Reputation: 36592

You want to grab all the TDs and filter for only the ones that don't have a visible element next to it.

Dang, that only works if there aren't any invisibles in the middle of the row.

Upvotes: 0

Related Questions