-3

I need the id of the child element alone which is clicked. If I use $(this).attr('id') it brings the id of the parent also.

Here is the code,

<body>
    <div id="divOne">
        <div id="divTwo">
            <div id="divThree">
                <div id="divFour">
                </div>
            </div>
        </div>
    </div>
</body>

I need the id of the div four alone when it is clicked

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77

4 Answers4

1

Use event.stopPropagation to stop the event from propagating to the parent divs:

$('div').click(function(e) {
  e.stopPropagation();
  console.log(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOne">
  <div id="divTwo">
    <div id="divThree">
      <div id="divFour">
      test
      </div>
    </div>
  </div>
</div>
31piy
  • 23,323
  • 6
  • 47
  • 67
0

You need to use event.stopPropagation(); to stop propagating to the parent element:

WORKING EXAMPLE

$(document).ready(function(){
  $('div').click(function(event){
    event.stopPropagation();
    console.log($(this).attr('id'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div id="divOne">
        <div id="divTwo">
            <div id="divThree">
                <div id="divFour">
                four
                </div>
            </div>
        </div>
    </div>
</body>

NOT WORKING EXAMPLE

$(document).ready(function(){
  $('div').click(function(event){
    console.log($(this).attr('id'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div id="divOne">
        <div id="divTwo">
            <div id="divThree">
                <div id="divFour">
                four
                </div>
            </div>
        </div>
    </div>
</body>

event.stopPropagation(); Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

use

console.log(event.target.id)

instead of

$(this).attr('id')

because this equals to element you bind on while event.target equals to the element triggered the event

xianshenglu
  • 4,943
  • 3
  • 17
  • 34
0

$("div").click(function(e) {
  console.log($(this).attr("id"));
  e.stopPropagation();
});