Rich Tier
Rich Tier

Reputation: 9459

jquery lowest nested selector

I would like to slideUp all children of ".sub-menu" selectors for the following code:

<div ID="browse_container">
    <div class="sub-menu">Root
        <div class="sub-menu">▷ English</div>
        <div class="sub-menu">▷ Maths
            <div class="sub-menu">Year 1</div>
            <div class="sub-menu">Year 2</div>
        </div>
        <div class="sub-menu">▷ Science</div>
    </div>
</div>

My jquery is:

$(document).ready(function() {
    $('.sub-menu').live('click', function(){
        $(this).children().slideUp()
    })
});

But this slides up "Root", as the sub items of, e.g., "english" are all children of "Root". Can I tell jquery to select the lowers nested "sub-item"?

Upvotes: 2

Views: 198

Answers (1)

sachleen
sachleen

Reputation: 31141

$(document).ready(function() {
  $('.sub-menu').on('click', function(event){
    event.stopPropagation();
    $(this).children().slideUp();
  });
});

Demo

You can stop the event from "bubbling up the DOM tree, preventing any parent handlers from being notified of the event."

Now when you click on Maths, only the children slide up.

Upvotes: 2

Related Questions