Suppose, we have this html where div element have 2 child p elements and 1 child anchor element.
<div>
<p> I am para one</p>
<p> I am para two</p>
<a href="http:nowheretogo.com">I am a link</a>
</div>
lets add css that will differentiate between div, a and p tag
div{ background:#abcdef; padding:20px; }
p{ background:#00ff00; margin:20px; }
a{ background:#00ff34; margin:20px; }
Now if you want your jQuery function to run on div but not on elements inside the div (p an a tags here). use
$('div').on('click', function(event) {
if (event.target !== this) {
event.preventDefault(); // for preventing anchor tag default functionality
return;
}else {
alert('Make love not war');
}
});
If you want to protect only one element inside div say anchor tag, here's how you can do it
$("div").click(function(event) {
if($(event.target).is('a')){
event.preventDefault();
return;
}else {
alert("Life is too short to grow old");
}
});
here is a JSFiddle link for your experiments
0 Comment(s)