This question has already been answered:

For example, there is a function

$(document).ready(function(){ $( '.element' ).someFunc(); }); 

Everything works fine, but if you add new elements with the .element class via JS, you will have to call it again. Is it possible to put tracking of the appearance of elements with the class .element and automatically apply this function to them?

Reported as a duplicate at Grundy. javascript Jan 10 at 11:22 am

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 .

  • one
    Immediately after creating and inserting an element in the DOM, you need to apply this function. Those. you need to find the place where the element is rendered in the DOM. - Misha Saidov
  • you will need to call it at the time you create the item. Otherwise it will not work - ThisMan
  • @ThisMan work out. - Beast Winterwolf

1 answer 1

 addButton = function() { $("body").append("<button class='buttons'>Hi</button>") } $(".buttons").on("click", addButton) $(document).on('DOMNodeInserted', function(event) { $(event.target).on("click", addButton) }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="buttons">Hi</button> 

  • One ready is indispensable. JQ will not keep abreast of new elements in the DOM. - Misha Saidov
  • @MishaSaidov corrected his answer (remembered how this handler is called). - Beast Winterwolf