tags:

views:

49

answers:

2

I write a simple piece of code that creates a div and assign it a class name:

$('#create_div').click( 
function() {    
  div = $("<div>").addClass("myClass");
  $("body").append(div); 
} 
);

Ok: after "create_div" button is fired the function appends the new div to body container.

Now... : How to select the new element created ? How do I reach it? I have tried:

$('.myClass').click( 
function() {    
  // do something 
} 
);

but it doesn't works. Thanks for the help!

+1  A: 
$('.myClass').live('click', 
function() {    
  // do something 
} 
);

Should bind to an element that is created after the DOM is loaded.

AutomatedTester
that's equivalent to using `.click()`. it's just a shorthand.
Anurag
That does exactly the same thing as his code. Did you mean `live()`?
Matti Virkkunen
Mattia
@matti i did mean `live()` thanks for pointing that out :)
AutomatedTester
A: 

This would also work:

  div = $("div").addClass("myClass"); //NOTE: not <div> !!
  $("body").append(div); 

  div.click(function(e) {
    //Do Something
  });
James Westgate