4
  • 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
    source share
    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
    source

    Try the following:

     $('li.curSelected').prevAll(":visible:first"); 

    prev() returns only the immediate element preceding the selected one. prevAll() returns all previous ones.

    +13
    source

    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
    source

    Here is my example. Works fine, any browser.

     var elem = $( some_thing ).next(); while( elem && elem[0] != undefined && !elem.is( ':visible' ) ) elem = elem.next(); if( elem && elem[0] != undefined ) elem.doSomething(); 
    0
    source

    Source: https://habr.com/ru/post/947081/


    All Articles