12

I have a statement adding a new div:

$('#dates').append('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>');

But I'd like to not only create element but also to assign on('click') action to it. Of course I could add generated id and then acces to created element by this id, but I feel that there is more beautiful solution.

Is it?

Roman Matveev
  • 563
  • 1
  • 6
  • 22

2 Answers2

14

You don't need to add an id and then ask jQuery to parse a selector to find the element. You can directly do this :

$('#dates').append(
    $('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>')
    .click(function(){
      // handle click
    })
);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

you can use jquery ON.. and also you can use class selector instead of id :) like $(".classname")

$('#dates').append('<div class="'+classname+'">'+dd+'<br /><span class="month_selector">'+dm+'</span></div>');

$('#dates').on('click','.'+classname, function(){
alert("on div click");
});

$('#dates').on('click','.month_selector', function(){
alert("on SPAN click");
});
rahul maindargi
  • 5,359
  • 2
  • 16
  • 23
  • 1
    If you use `.on()` you can do it once when the document is ready, you don't have to do it again when the element is added. – Barmar May 24 '13 at 07:39