Dynamically added DOM element don't get click event bounds to them as they have to exist before the event is created, you need to use jQuery's event delegation in order to target elements that exist after the DOM has loaded.

If you are adding the button dynamically, then it won't be present when the page loads, so this:

$(".mybtn").on("click", function(){
console.log("Clicked!");
});

won't work.

What you need to do is to attach the handler to an element that is present when the DOM is loaded (e.g. document), then specify a selector (e.g. ".mybtn") with which to filter the descendants of the selected elements which trigger the event.

Hi @pullo and @chris.upjohn, Thank you so much your solution is working...:)...@pullo, thank you for explaining me

What you need to do is to attach the handler to an element that is present when the DOM is loaded (e.g. document), then specify a selector (e.g. ".mybtn") with which to filter the descendants of the selected elements which trigger the event...this helps me a lot.

One more thing i couldn't understand what is the difference between the .parent and .parents,when to use this .parent or .parents when traversing the DOM ?

Many regards

Pullo
—
2013-08-10T10:59:02Z —
#5

Hey jemz,

jemz said:

i couldn't understand what is the difference between the .parent and .parents,when to use this .parent or .parents when traversing the DOM ?

.parent() gets the parent of each element in the current set of matched elements..parents() gets the ancestors of each element in the current set of matched elements.Both results sets can optionally be filtered by a selector.

The biggest difference between the two methods is that .parent() only travels a single level up the DOM tree.