简体   繁体   中英

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM