Andy B
Andy B

Reputation: 205

jQuery parents/children in nested lists

In jQuery, parents() and children() are not behaving like I expect with nested lists. An example:

<ul>
    <li>item 1
        <ul>
            <li>item a</li>
            <li>item b
                <ul>
                    <li>item i</li>
                </ul>
            </li>          
            <li>item c</li>
        </ul>
    </li>
    <li>item 2</li>
</ul>

and the javascript:

$( 'li' ).click(function(event) {
    $( 'ul' ).not( $(this).parents() ).hide();
    $( this ).children().show();
});

If I click "item b" then 'item i' hides. It seems that "item i" is a child of "item b" and should be shown by $(this).children().show()

Do I have a syntax problem, or am I misinterpreting children/parents in the DOM?

See https://jsfiddle.net/8o71yfpf/ for a working example.

Upvotes: 0

Views: 542

Answers (1)

Vikram
Vikram

Reputation: 3351

you should use event.stopPropagation();

when you click on inner li you are also clicking on parent li.

updated https://jsfiddle.net/8o71yfpf/2/

it may help to understand DOM traversal http://www.richfinelli.com/understanding-dom-traversal-in-jquery/

Upvotes: 4

Related Questions