user6733315 user6733315 - 11 months ago 40
HTML Question

Adding click event to button is working but adding click to same element doesn't work

I added click event to button . it is working fine.

$("#button1").click(function(){var elem = $("<p></p>").text("hello").attr("id","created");
$("#button2").click(function(){ $("#created").hide();});

But adding click event to new created element not working.

$("#button1").click(function(){var elem = $("<p></p>").text("hello").attr("id","created");
$("#created").click(function(){ $("#created").hide();});

Can someone explain. i am expecting. I create only one element and when i click on that element it should hide. thats it. This question is not about id and class . just create one element and try to experiment what i am saying. I want when i click on created paragraph it should hide itself.

Answer Source

The created element is a newly created element so at the time of page loading the DOM parser is not able to find the element and bind the click event that is the reason why your second case is not working. Here is the solution.

var elem = $("<p></p>").text("hello").attr("class","created");

              $( ".created" ).bind( "click", function() {
$( ".created" ).hide();


What i did here is while creating the element I am manully binding a click event to the element. If you create element with ID, then it will work only for the first time. Second time when you click the button it will create a new element with same id and the code wont work. So in my example i have used class instead of ID. Here is the working copy