jQuery | Click event does not work on dynamically created HTML elements

|
| By Webner

Solution: Suppose we have the following HTML and jQuery code:

HTML:

<div id="container">
<button id="1" class="createNewElement">Button</button>
</div>

jQuery:

$('.createNewElement').click(function(e)
{
alert("Element with id " + $(this).attr('id') + " is clicked!"); // tells id of button clicked
newElementId = parseInt($('div button').last().attr('id')) + 1;  // id for new element

$('div').append('<button id="'+newElementId+'" class="createNewElement">New Element');
// New element button created
});

Following screen is displayed by above HTML content:

On clicking “Button”, alert message is displayed and new button is be created as shown:

But we face a problem when we click on newly created buttons, no alert message is displayed and no new element is created.

We are firing click event based on class of buttons. All buttons have same class “createNewElement”.
jQuery click function works only with already created elements on page load. Click function does not work with dynamically created elements.

To make click event in jQuery to be working for newly created elements, we have to use jQuery On function as follows:

$('div').on('click', '.createNewElement', function(e)
{
// jQuery code is same as above
}

Now, here we have used On function on the container which contains elements. In this function, the first parameter is event name, the second parameter is class name of elements.

Now, click event for newly created elements is also working.

Leave a Reply

Your email address will not be published. Required fields are marked *