SamuraiJack
SamuraiJack

Reputation: 5539

How to select the clicked child element within a parent element in Jquery?

I have a parent div within which elements are added dynamically. I want to find out the class of the element which was clicked, if none of the child element was clicked but parent was clicked then I would like to get the class of parent element.

$(document).ready(function() {
  $('.parent').on('click', function(event) {
    // event.stopPropagation();
    alert($(this).attr('class'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div class='parent'>Parent//clicking here should alert parent
  <ol>
    <li class='type1'>NEW</li>//clicking on this should alert type 1
  </ol>
</div>

Upvotes: 0

Views: 1309

Answers (1)

Amin Jafari
Amin Jafari

Reputation: 7207

try this:

$(document).ready(function() {
  $('.parent').on('click', function(event) {
    // event.stopPropagation();
    alert($(event.target).attr('class'));
  });
});

this will get the target tag of the clicked position.

see the DEMO

Upvotes: 1

Related Questions