user3202738
user3202738

Reputation: 3

jQuery select only the element with $(this)

I'm using a bit of code to slidetoggle ul:s in form of an hierarchy. Foreach click on a li containing a ul the ul should slidetoggle. I'm trying to use $(this) to select the element that has been clicked, but instead it chooses all the elements using the same class. How should I write my code to make it only choose one element?

$(document).ready(function(){
    $(".list").click(function(){
        $(this).children('ul').slideToggle();
    });
});

Upvotes: 0

Views: 55

Answers (1)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

That is caused because a click in a children element is also a click in the parent, it proc multiple events.

You can prevent that with e.stopPropagation but you also need to change your selector. Try this :

$(document).ready(function(){
    $("#nestedlist li").click(function(e){
        e.stopPropagation()
        $(this).children('ul').slideToggle();
    });
});

http://jsfiddle.net/Tz85y/1/

Upvotes: 1

Related Questions