mattpark22
mattpark22

Reputation: 751

How can I make my jQuery 'Click' function run for the only the immediate li, and not the child li's

I've got:

$('#accordion > li).click(function () {

But it run's if the #accordion li ol li is clicked as well.

Here's the html markup:

<ul id="accordion"> 
   <li id="test1">
       <a href="#">Test</a>
       <ol>
            <li>
            <a href="#">test</a>     
            </li>
       </ol>
    </li>
</ul>

Upvotes: 2

Views: 709

Answers (3)

Tak
Tak

Reputation: 11704

An easier solution might be:

$('#accordion > li:not(li li)').click(function () {});

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

You could use stopImmediatePropagation() from jquery to avoid it bubbling up.

$('#accordion > li).click(function (event) {
     event.stopImmediatePropagation();
     //do what you need to do

}

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237837

The problem is that the events on the descendant elements bubble up to the ancestor element. Stop this by checking whether the originating element's (event.target) first ancestor li is the one where the function is being handled:

$('#accordion > li').click(function (event) {
    if ($(event.target).closest('li').is(this)) {
        // it's the right one
    }
});

See

Upvotes: 3

Related Questions