1

my code :

$('div').on('click',function(){
    checkEl = $(this).attr('id');
    console.log(checkEl);
});

So each time div is clicked it schould throw a id of clicked element...

But.. on console.log i got like 3/4/5/6 elements depends from where i cliced...

My output is id of expected div but also parent div are displayed...

How to get id of exactly clicked element?

$(function(){
$('div').on('click',function(){
    checkEl = $(this).attr('id');
    console.log(checkEl);
    })
    })
#main{
position:relative;
width:300px;
background-color:red;
}
div{
position:relative;
border:1px solid gray;
padding:15px;
width:100%:
}
#one{
background-color:black;
}
#two{
background-color:blue;
}#three{
background-color:orange;
}#four{
background-color:yellow;
}#fifth{
background-color:purple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="one">
<div id="three">
<div id="four">
<div id="fifth">
</div>
</div>
</div>
</div>
</div>
Piotr Mirosz
  • 846
  • 9
  • 20
  • 3
    Events bubble up the DOM tree; so clicking on `#fifth` will, in turn, pass that click event to every ancestor `
    ` element. (I'm not posting an answer because I'm sure this is a dupe, and I'm looking for that.)
    – David Thomas Feb 04 '19 at 17:50

4 Answers4

3

To avoid that the event is also triggered for parent elements, add a call to stopPropagation:

$('div').on('click',function(e) {  // <-- argument
    checkEl = $(this).attr('id');
    console.log(checkEl);
    e.stopPropagation(); // <---
});
trincot
  • 317,000
  • 35
  • 244
  • 286
3

Your problem is that all of your nested divs have the onclick handler, so they all trigger. If you only want the innermost, you can use the following.

$('div').on('click',function(ev){
    ev.stopPropagation()
    checkEl = $(this).attr('id');
    console.log(checkEl);
});

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

nathan.medz
  • 1,595
  • 11
  • 21
1

You need to mitigate event propagation. Basically, since the DIVs are nested, the click event is called on the inner-most div and propagates up through the parent elements all the way to the DOCUMENT.

Calling event.stopPropagation() in the click event handler prevents this behavior.

$('div').on('click',function(event)
{
    checkEl = $(this).attr('id');
    console.log(checkEl);
    event.stopPropagation();
});
Sheridan Bulger
  • 1,214
  • 7
  • 9
0
$(function() {
$('div').on('click',function() {
    event.stopPropagation();
    checkEl = $(this).attr('id');
    console.log(checkEl);
    })
})
Marcelo Vismari
  • 1,147
  • 7
  • 15