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?
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?
Share Improve this question edited Jun 21, 2014 at 15:02 mikelamar 1881 silver badge6 bronze badges asked Jun 21, 2014 at 14:30 user3763026user3763026 833 silver badges11 bronze badges 3- But ul will have li after all.What do u mean by Click on ul – Pratik Joshi Commented Jun 21, 2014 at 14:32
- jsfiddle/v5eh8/1 Check this fiddle.UL has LI so thought you click on li , it will be as if UL is clicked – Pratik Joshi Commented Jun 21, 2014 at 14:34
- I mean jquery click event will affect except all li. – user3763026 Commented Jun 21, 2014 at 14:35
2 Answers
Reset to default 4You 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/S67Uu/2/
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();
});