This code does not work on all elements:

$('body').click(function (event) { t=event.target||event.srcElement; alert(t.tagName); }); 

Need more reliable method

Reported as a duplicate by Visman , fori1ton , aleksandr barakin , user194374, Streletz July 9 '16 at 19:42 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • The above example should work without problems (except that jQuery was just created in order to abstract the user from browser differences, so it makes no sense to define the target with your hands). Make an example on jsfiddle and explain in what situations the given code does not work for you. It is possible that some other handler intercepts the event and prohibits its ascent. - Alexey Ukolov
  • one
    Documentation $(element).on('click', function (event) { ... }); - Mr. Black

1 answer 1

Through .click () the element is already found in the DOM, and through .on () the jquery searches for the specified .b element with each click

 element = $("<button class='b'>element</button>"); $('button').click(function() { $('body').append(element); }); $('body').on('click', '.b', function() { console.log('b click'); }); 
 <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script> <button>Создать элемент</button> 

  • How does .click () differ from .on () in this section? How does your delegation differ from what the author cited in the question? - Alexey Ukolov
  • one
    @AlexeyUkolov, in theory through .click() element is already found in the DOM. And through .on() jquery searches for the specified .b element with each click. - Mr. Black
  • .click () is a wrapper over .on (). In a question there is an unnecessary implementation of delegation, but in general the same as .on ('click', '.class', handler) - Alexey Ukolov
  • I don’t know exactly why this happens, but @Doofy is right, because if an element was added to the DOM after loading the script with the .click () method, then .click () does not work, only $ ('body') will work. ('click') - Romanzhivo