user081608
user081608

Reputation: 1133

collapsing a list using jquery

I have a list I am trying to collapse and am having trouble once I get lower in the hierarchy. Here is my html:

<ul class="list">
    <li>
        <a>Categories</a>
        <ul>
            <li>
                <a>Parent</a>
                <ul>
                    <li><a>Child</a></li>
                    <li><a>Child</a></li>
                    <li><a>Child</a></li>
                </ul>
            </li>  
            <li>
                <a>Parent</a>
                <ul>
                    <li><a>Child</a></li>
                    <li><a>Child</a></li>
                    <li><a>Child</a></li>
                </ul>
            </li>  
            <li>
                <a>Parent</a>
                <ul>
                    <li><a>Child</a></li>
                    <li><a>Child</a></li>
                    <li><a>Child</a></li>
                </ul>
            </li>  
            <li>
                <a>Parent</a>
                <ul>
                    <li><a>Child</a></li>
                    <li><a>Child</a></li>
                    <li><a>Child</a></li>
                </ul>
            </li>            
        </ul>                
    </li>
</ul>

Heres my jquery

$( document ).ready(function() {
    $('.list > li a').click(function(){
        $(this).parent().find('ul').toggle();
    });
});

And here is a jfiddle: http://jsfiddle.net/u7bczqup/

Once you click on Categories the Parents come down. When this happens, all the children of the parents are shown and not hidden. Why are these ones not hidden? Ive tried adjusting my jquery but that causes it to not work at all.

Upvotes: 0

Views: 67

Answers (3)

Tzvetan Koshutanski
Tzvetan Koshutanski

Reputation: 36

You're searching for all unordered list elements in the method .find('ul') that are direct descendants. It should be .find('ul:first-child') ore more precisely .children(ul:first) so it would be

$( document ).ready(function() {
    $('.list > li a').click(function(){
        $(this).parent().children('ul').toggle();
    });
});

for more refer to jquery find method

Upvotes: 0

Stephen King
Stephen King

Reputation: 836

They are not hidden because jquery find searches any descendants below it and then you are toggling them, you should use children().

Try this:

$(this).parent().children('ul').toggle();

http://jsfiddle.net/u7bczqup/1/

https://api.jquery.com/children/

Upvotes: 1

hopkins-matt
hopkins-matt

Reputation: 2833

Give this a shot.

JS:

$( document ).ready(function() {
    $('.list > li a').click(function(){
    $(this).next('ul').toggle();
    });
});

The issue with using .find() is that it is finding all the ul element. You can check this by adding this line: console.log($(this).parent().find('ul')); This will print all the ul tags it is "finding" to the console. Because it is finding all of them, it is toggling all of them.

Upvotes: 1

Related Questions