Show/hide <li> by jQuery
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(...);
James
Updated on July 05, 2022Comments
-
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 nextli.dropdown
, should become visible. And opposite action when we click it again - hide<li>
without classdropdown
.How do I do this?
-
James almost 13 yearsI cant change html structure.
-
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.