amateur amateur - 3 months ago 10
jQuery Question

assigning click event to div but not anchor within it

A jquery question.

I have a div that contains text and an anchor tag.

I want to assign a click event to the div tag and its content EXCLUDING the anchor tag.

So when I click on the div, an alert window pops up. But if I click the anchor (thats within the div), the alert should not occur.

The div would be something like this:

<div id="myDiv">
This is the content of the div.
<img src="blah.jpg" />
<a href="somewhere.html">Click here</a>.
Some more content.
</div>


Any ideas? I am using jquery to assign the click event to the div.

Answer

You can check the target of the click since the <a> has no children, for example:

$("#myDiv").click(function(e) {
  if(e.target.nodeName == 'A') return;
  //click handler code
});