text
  • text
  • text
  • text
  • text
  • Show / hide <li> jQuery

    I have html like

    <ul>
    <li class="dropdown">text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    <li class="dropdown">text</li>
    <li>text</li>
    <li>text</li>
    <li class="dropdown">text</li>
    <li>text</li>
    <li>text</li>
    <li>text</li>
    </ul>
    

    CSS

    li {display:none;}
    li.dropdown {display:block;}
    

    When we click on li.dropdown, all <li>without classes, from current to next li.dropdown, should become visible. And vice versa, when we click it again - hide <li>without a class dropdown.

    How to do it?

    +3
    source share
    4 answers

    The correct way to do this would be with a submenu, therefore:

    <ul>
        <li class="dropdown">text
            <ul>
                <li>text</li>
                <li>text</li>
                <li>text</li>
                <li>text</li>
            </ul>
        </li>
        etc...
    </ul>
    

    Then you can do

    $('li.dropdown').click(function() {
        $(this).find('ul').slideToggle('slow');
    });
    

    Otherwise, you will need to use nextUntil:

    $('li.dropdown').click(function() {
        $(this).nextUntil('li.dropdown').slideToggle('slow');
    });
    

    This drawback will be hiding each of the nested elements liseparately, and not as a block. Do the first if you can.

    +7
    source

    I would recommend using the nested lik this list structure:

    <ul>
    <li class="dropdown">text
        <ul>
            <li>text</li>
            <li>text</li>
            <li>text</li>
            <li>text</li>
        </ul>
    </li>
    <li class="dropdown">text
        <ul>
            <li>text</li>
            <li>text</li>
        </ul>
    </li>
    </ul>
    

    Create this CSS:

    li.dropdown ul {
        display : none;
    }
    

    / :

    $('li.dropdown').click(function() {
        $(this).children('ul').toggle();
    });
    
    +2

    $dropdown, :

    $dropdown.next( "li:not(.dropdown)" ).hide();
    

    .dropdowns;

    .dropdown, :

    $dropdown.next("li").each(...);
    
    +1
    $("li.dropdown").click(function() {
        $(this).nextUntil(".dropdown").toggle();
    });
    

    Fiddle

    +1
    source

    All Articles