0

How to get the id of the element clicked using jQuery this question have the answer of get the id of clicked element.

But it gives the all id.

For example

  <div id="major">
    <div id="two">  </div>
  </div>

When clicking the div two I want to get the id only one which is two. But the following script will give parent id also.

    $("body").on('click','div',function() 
    {   
        alert(this.id);
    });    //It alerts the two and major. But i want two only.

For this, purpose i tried to put the some undeclared function it gives result what i expect. For example

$("body").on('click','div',function() 
{   
    alert(this.id);
    mkh(); #undeclared function
});   

Is there any inbuild method for to do it.? JS Fiddle

Community
  • 1
  • 1
mkHun
  • 5,891
  • 8
  • 38
  • 85

4 Answers4

3

You need to stop parent event propagation to child element:

$("body").on('click','div',function(e){   
  e.stopPropagation();
  alert(this.id);
  mkh(); #undeclared function
});   

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

Use event.target object.

$("body").on('click', 'div', function(e) {
  alert(e.target.id);
  e.stopPropagation();
});
#two {
  width: 100px;
  height: 100px;
  background: blue;
}
#major {
  width: 500px;
  height: 500px;
  background: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="major">
  <div id="two"></div>
</div>
rrk
  • 15,677
  • 4
  • 29
  • 45
1

Not changing the target element.

Event object can be used to serve the purpose. $(event.target) will give current target element Using event.stopPropagation() to stop propagation(bubbling) of event when you click on inner div. Otherwise you will see two alerts of inner & outer div

    $("body").on('click','div',function(event) 
    {   event.stopPropagation();
   var _getId = $(event.target).attr('id');
    alert(_getId);

    });   

Check this jsfiddle

brk
  • 48,835
  • 10
  • 56
  • 78
0

This is not too hard. Watch this:

$("body").on('click','#two',function() 
    {   
        alert(this.id);
    });
MysterX
  • 2,318
  • 1
  • 12
  • 11