Sunny
Sunny

Reputation: 932

Add new css class to dynamically generated images and div in jquery

I'm creating some dynamic images and divs in jquery.

user = wrapper.append("<div class='user-container' />"); 
user.append("<img class='user-img' src='" + path + "'/>;

How do I apply the classes user-img and user-container using my external css?

Thanks, Ansh

Upvotes: 1

Views: 999

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

The append method returns the current jQuery object itself and not the appended element object.

You can define the HTML content and other attributes by wrapping the div HTML using jQuery.

wrapper.append($("<div/>",{
  html : "<img class='user-img' src='" + path + "'/>",
  class : 'user-container'
})); 

Or you can do it in a reverse manner to keep the reference of appended element using appendTo() method in jQuery.

var wrapper = $("<div class='wrapper'></div>").appendTo("main"); 
var user = $("<div class='user-container' />").appendTo(wrapper); 
user.append("<img class='user-img' src='" + path + "'/>");

Upvotes: 2

Related Questions