I’m attempting to create a “filterable” list of items. The user should be able to click on a list element (the parent), which would hide all other parent elements and show the “children”.
An example of the html is:
<ul class='parent_list'>
<li>Parent 1</li>
<ul class='child_list'>
<li>Child 1</li>
<li>Child 2</li>
</ul>
</li>
<li>Parent 2</li>
<ul class='child_list hidden'>
<li>Child 1</li>
<li>Child 2</li>
</ul>
</li>
</ul>
My jQuery code is:
$('.parent_list li').click(function(){
$(this).siblings().addClass('hidden');
$(this).children().removeClass('hidden');
});
Of course, you can probably tell by the javascript that I don’t have too much experience with things like this. I’ve tried searching for a bunch of different examples on Google and haven’t been able to get anything to work as of yet. Any tips?
Thanks!
Try this:
And change your HTML to remove the extra
</li>after “Parent1” and “Parent2”:When the direct children of
.parent_listare clicked, it’ll hide all children lists except for it’s own. I used the.hide()and.show()methods since they simply toggle the element’sdisplayproperty.Here’s the jsfiddle to play around with.