Get previous visible jquery element
I have <ul> how
<ul> <li>1</li> <li>2</li> <li>3</li> <li style="display:none;">4</li> <li class="curSelected">5</li> <li>6</li> </ul> Now from <li> 5 I want a link to the previous visible element ie <li> 3
How can I get it?
I tried $('li.curSelected').prev(":visible:last");
But that does not work.
Please, help.
+6
4 answers
You can use .prevUntil() to search (but not including) the first visible element, then use .prev() :
$('.curSelected').prevUntil(':visible').prev() Update
As stated in the comments, this will not work if the previous item is already visible. Unfortunately, there is no optimal jQuery for this, so here is an alternative:
$prev = $('.curSelected') do { $prev = $prev.prev(); } while ($prev.length && $prev.is(':hidden')); +5
Since jQuery traverses dom using prev from the current to the first, but returns only one element (previous), you should use .prevAll .
$("li.curSelected").prevAll(":visible:first"); See the working script for this example.
+4