Maroof Maroof - 1 year ago 110
HTML Question

Adding event Listener to Dynamically Added HTML Elements

I have the HTML

<input type="button" class="btnx" value="click me">

and the attached JS file

var newbtn = "<input type='button' class='btnx' value='click me'>";

When I click on the button 1 new buttons are append to the body, but when I click on the new buttons(button 2 or button 3) why no more buttons are formed.

I googled and found to use ".on()" but still can't figure out why it is not working.

JSFiddle link:

Answer Source

You can use $('body').on('click', '.btnx', ...) for that:

$("body").on("click", '.btnx', function(){
	var newbtn = "<input type='button' class='btnx' value='click me'>";
<script src=""></script>
<input type="button" class="btnx" value="click me">

Explanation regarding your code:

The problem with your code was that the new element that you added to the DOM tree didn't have the click event attached to it.
The way to make this work is to attache the click event to the body element, and use the .btnx selector. This way the code will work with every click you have, also for new elements that you add.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download