How to use jquery selectors to select parent only but exclude child
HTML
<div id="container">
<div class="element">
<img src="something.jpg"/>
<a href="somelink">Some link</a>
<p>Blah blah...</p>
</div>
<div class="element">
<img src="something2.jpg"/>
<a href="somelink2">Some link2</a>
<p>Blah blah...</p>
</div>
</div>
JQuery:
How can I trigger alert(“Hi”) only if user clicks on (div “element”) but not when < a > and < img > are clicked
$("#container").delegate(".element", "click", function(){
alert("Hi");
});
Events bubble up the DOM unless you explicitly stop their propagation. I recommend that you try to work with this, not against it. That said, if you insist, examine
event.targetto make sure that thediv.elementwas clicked, and not one of its children:http://jsfiddle.net/mattball/JMDLq/