Show/hide <li> by jQuery

25,223

Solution 1

The correct way to do this would be with submenus, so:

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

You can then do

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

Otherwise, you'll have to use nextUntil:

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

This will have the disadvantage of hiding each of the nested li elements individually, rather than as a block. Do the first if you can.

Solution 2

I would recommend using a nested list structure lik this:

<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>

Creat a CSS like this:

li.dropdown ul {
    display : none;
}

And then only show/hide the nested unordered lists:

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

Solution 3

If you have the item in $dropdown variable then you can use this:

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

That will hide all not .dropdowns;

To do this until the next .dropdown you will need to use:

$dropdown.next("li").each(...);

Solution 4

$("li.dropdown").click(function() {
    $(this).nextUntil(".dropdown").toggle();
});

Fiddle

Share:
25,223
James
Author by

James

Updated on July 05, 2022

Comments

  • James
    James almost 2 years

    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 the <li> without classes, from the current to the next li.dropdown, should become visible. And opposite action when we click it again - hide <li> without class dropdown.

    How do I do this?

  • James
    James almost 13 years
    I cant change html structure.
  • Daff
    Daff almost 13 years
    @Rooney You can still change the HTML structure with jQuery (if you really need to show/hide them as a block). Otherwise nextUntil should work fine.