user3763026
user3763026

Reputation: 83

Fire ul tag click event not li with jquery

How can affect click event only ul tag not all li with jQuery?

<!-- HTML -->
<ul class="wrap">
    <li>test1</li>
    <li>test2</li>
    <li>test3</li>
</ul>

I tried jquery like this.But it doesnt work.

//Javascript
jQuery("ul.wrap").not(jQuery("ul > li")).click(function(){
      //fire only ul
});

How can we do this?

Upvotes: 4

Views: 3347

Answers (2)

John Skoubourdis
John Skoubourdis

Reputation: 3289

You can simply do it with this code:

jQuery('.wrap').click(function (event) {    
    if ( !$(event.target).is( "li" ) ) {
        console.log('ul clicked!');
    } 
});

You can see an example with background colors that shows the ul and the li here: http://jsfiddle.net/S67Uu/2/

Upvotes: 4

Rory McCrossan
Rory McCrossan

Reputation: 337713

Events 'bubble' up the DOM to their parent elements. What you need to do is attach the event to the ul, and another event on the child li elements which uses stopPropagation():

jQuery("ul.wrap")
    .on('click', function(){
        // do something...
    })
    .on('click', 'li', function(e) {
        e.stopPropagation();
    });

Upvotes: 3

Related Questions