Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently find the next visible table row with jQuery

In a table with some rows hidden, I want to get the next visible row, if one exists. This will do the job:

row = $(selectedRow).nextAll(':visible');
if ($(row).length > 0)
    selectedRow = row;

but it is very slow when many rows follow the selected row. A scripted approach is:

var row = $(selectedRow).next();
while ($(row).length > 0 && !$(row).is(':visible'))
    row = $(row).next();
if ($(row).length > 0)
    selectedRow = row;

This is much faster, but there's got to be an elegant all-jQuery approach I can use.

like image 948
Marshall Morrise Avatar asked Dec 13 '11 19:12

Marshall Morrise


2 Answers

Based on the helpful suggestion from mblase75, here is the most elegant solution I've found:

var row = $(selectedRow).next(':visible');

if ($(row).length == 0)
    row = $(selectedRow).nextUntil(':visible').last().next();

if ($(row).length > 0)
    selectedRow = row;

Often (in my case), the table isn't filtered, so the next row is visible much of the time. When it is not, nextUntil() yields a non-empty set of non-visible rows. Selecting the last row in that set and then the next row following it gives the next visible row in the table, if there is one.

like image 108
Marshall Morrise Avatar answered Sep 21 '22 09:09

Marshall Morrise


Just ran into exactly the same situation. Based on Marshall Morrise's answer, if you want a one-liner, you can try...

selectedRow = $(selectedRow).nextUntil(':visible').add(selectedRow).last().next();

The new bit here is the .add(selectedRow) which prevents us from trying to find the next() of an empty jQuery element. Only remaining problem is the last if in Marshall's post - unfortunately an empty jQuery element is still truthy.

like image 31
Erwin Wessels Avatar answered Sep 21 '22 09:09

Erwin Wessels