Two-1
  • Two-2

    Show hidden li based on class

    I have the following list structure:

    <ul>
        <li>One</li>
        <li>Two
            <ul>
                 <li class="active">Two-1</li>
                 <li>Two-2</li>
            </ul>
        </li>
        <li>Three
            <ul>
                <li>Three-1</li>
            </ul>
        </li>
    </ul>
    

    with the following CSS:

    ul li ul{
        display:none;
    }
    ul li:hover ul{
        display:block;
    }
    

    I would like: When the li class is active, the entire structure is displayed until the active class is displayed.

    therefore, if the following is shown below:

    • One
    • Two
      • Two-1
      • Two-2
    • Three

    I would like to either implement a CSS or jQuery implementation (or a mixture of the two).

    +3
    source share
    4 answers

    You can show active parents using .parents()or :has()when the page loads like this:

    $(function() {
      $('.active').parents().show();​​​​​​​​​
      //or..
      $(':has(.active)').show();​​​​​​​​​
    });
    

    Any of them works with any number of levels in depth, the first will be a little faster, though.

    +4
    source

    , , jQuery?

    ​$('.active').parent().show().parent().parent().show();​​​​​​​​​
    
    +1

    :has() :

    $("ul:has(li.active)").show();
    

    This selector finds any element <ul>that has a child <li>with a class active.

    +1
    source

    There are so many ways to achieve this, I prefer the others posted here, but here are two more.

    $('li.active').parent().css('display', 'block');
    $('ul:parent').has('li.active').css('display', 'block');
    

    They are more specific and will only work on lists.

    You can also use show () instead of css ('display', 'block'). It is probably better if the element is hidden again, they will return to their previous displayed value.

    0
    source

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


    All Articles