There are two problems with one -liners mentioned in other answers:
- They miss the case when there are no invisible rows. In that case, nextUntil does not return any elements. Below is the code that fixes this issue.
- If you are using specific class name, instead of jQuery's default show/hide then also it doesn't seem to work reliably.
Below code fixes both of above issues with other answers:
//invisibleRowClassName parameter is optional
function nextVisibleSibling(element, invisibleRowClassName) {
var selector = invisibleRowClassName ? (":not(." + invisibleRowClassName + ")") : ".visible";
var invisibleElements = element.nextUntil(selector);
if (invisibleElements.length === 0) {
return element.next();
}
else {
return invisibleElements.last().next();
}
}
And here's the code to get previous visible element as well.
//invisibleRowClassName parameter is optional
function prevVisibleSibling(element, invisibleRowClassName) {
var selector = invisibleRowClassName ? (":not(." + invisibleRowClassName + ")") : ".visible";
var invisibleElements = element.prevUntil(selector);
if (invisibleElements.length === 0) {
return element.prev();
}
else {
return invisibleElements.last().prev();
}
}