azgolfer
azgolfer

Reputation: 15137

jQuery how to make click handler always reference the parent?

Let's say I have a simple parent and child nodes like this:

<div id="parent">
    <span id="child">Test</span>
<div>

And I have a jQuery click handler like this:

$('#parent').click(function (e) {
   alert(e.target.id);
});

If I click on the text span, I will get alert 'child'. If I click outside the span but within the parent div, I get alert 'parent'.

What do I need to do, if I want the behavior to change to: If I click anywhere within the parent div, whether it's on the text span or not, I want e.target to be referenced to the parent, and thus get alert of 'parent'?

Upvotes: 0

Views: 77

Answers (1)

Ram
Ram

Reputation: 144729

You can either use the this keyword (this.id) or read the currentTarget property of the event object, ie. e.currentTarget.id.

Upvotes: 1

Related Questions