Select every visible last child in jQuery

2020-07-06 03:08发布

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

4条回答
神经病院院长
2楼-- · 2020-07-06 03:25

You can do it:

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

See a full example (jQuery 1.2+ compatible)

查看更多
可以哭但决不认输i
3楼-- · 2020-07-06 03:27

to get every last visible them you can do something like

$('table tr').each(function(){
    console.log($(this).find('td:visible:last'))
})
查看更多
你好瞎i
4楼-- · 2020-07-06 03:35

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; 
})
查看更多
Viruses.
5楼-- · 2020-07-06 03:47

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.

查看更多
登录 后发表回答