Question

I need get the id of my dynamic created element inside a div. I'm looking for a way to get it's id by clicking it. Example:

$("#div").on("click", '*', function () {
    alert($(this).id);
});

The element can be an image, link, button, etc... I need to dynamic bind click to it, and get the id when gets clicked.

I use append to add sub elements to div.

$("#div").append(element);

Elements are right shown, but i can't retrive the ids.

Is there anyway to get it?

Example in jsfiddle: http://jsfiddle.net/StTvn

Was it helpful?

Solution

http://jsfiddle.net/StTvn/2/

changed the listener selector and it works

     $("#myDiv").on("click", "*", function () {
     txt = $(this).attr('id');
     alert(txt);
 });

as a side note, id that start with a number are not valid html - you might want to change the way you generate them like this:

el.id=  "img" + i.toString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top