Mattia
Mattia

Reputation: 3

How select an element by class name, previously loaded in DOM

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!

Upvotes: 0

Views: 147

Answers (2)

James Westgate
James Westgate

Reputation: 11464

This would also work:

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

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

Upvotes: 0

AutomatedTester
AutomatedTester

Reputation: 22438

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

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

Upvotes: 1

Related Questions