1

I have a very annoying problem, which might be a product of my poor knowledge of javascript and jQuery.

I have a list that uses recursion to enable a hierarchy-structure, it looks as follows

$(function (){
    $('#foo').click(function() {
        $(this).children('ul').slideToggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li id='foo'>A
        <ul>
            <li id='foo'>B
                <ul>
                    <li>
                        Sub-sub
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

I'm trying to accomplish a collapse function, so that when the user clicks on 'A' all the children elements collapses, and if she clicks the 'B' node all of 'B's children collapses. But however I try I always end up having all of the lists with id = 'foo' collapsing.

In my eyes, $(this).children('ul').slideToggle(); will collapse the children, since $(this) points to the list element clicked...?

Been at this for far to long now, would love some help!

mpma
  • 35
  • 4

1 Answers1

0

Here you go... No change in HTML. But like other suggested, you need to have unique ID's

$(function (){
    $('li').click(function(event) {
        event.stopPropagation();
    $(event.target).children('ul').slideToggle();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li id='foo'>A
        <ul>
            <li id='foo'>B
                <ul>
                    <li>
                        Sub-sub
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>
MarsOne
  • 2,155
  • 5
  • 29
  • 53