How would you appropriately code the jquery for the below list containing the <a> tags. I’m having two problems.
-
When I click the parent list item to reveal the child item, the parent item disappears and is simply replaced by an indented child item on the same line.
-
Somewhat related, I can for some reason click the last element of “1” “2” “3” and “4” resulting in the list actually disappearing. How can i fix this problem?
HTML:
<div class="main_list">
<ul>
<li><a href="#">1.</a>
<ul>
<li><a href="#">1.1</a>
<ul>
<li><a href="#">1.1.1</a></li>
</ul>
</li>
</ul>
<li><a href="#">2.</a></li>
<li><a href="#">3.</a>
<ul>
<li><a href="#">3.1</a></li>
<li><a href="#">3.2</a></li>
</ul>
<li><a href="#">4.</a>
<ul>
<li><a href="#">4.1</a>
<ul>
<li><a href="#">4.1.1 </a></li>
<li><a href="#">4.1.2 </a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
JQUERY:
$(document).ready(function(){
// only show top level elements to begin
$("ul ul").hide();
$("li").click(function(){
$(this).children().toggle(500);
return false;
});
});
Use
children("ul")to only toggle theulchildren of the parent itemli. Otherwise, you’ll toggle the parent item,<a href="#">1.</a>, which is also a child ofli:DEMO.