jstandshigh jstandshigh - 18 days ago 7
CSS Question

Dynamically create multiple divs and assign different css property for each using jQuery

I am stuck with an issue where I am not able to create multiple divs with different css attributes using a loop. It will be really helpful if someone guide me.

for(var i=0;i<array.length;i++)
{
....
....
....
$(".container").append('<div class="event" ><a>Sample text</a></div>');
$(".event").css("top",start+"px");
$(".event").css("width","94%");
$(".event").css("height",heightVal+"px");

}


I am only getting one div created inside my container. I think the issue is with the way I am appending my child divs.

Thank you in advance.

Answer
$(".container").append('<div class="event" ><a>Sample text</a></div>');
$(".event").css("top",start+"px");
$(".event").css("width","94%");
$(".event").css("height",heightVal+"px");

You need to contextualize your lookups. You are creating an event in the container, but then you are selecting every event to change it's css. Change the logic to possibly...

var $event = $('<div class="event" ><a>Sample text</a></div>');
$(".container").append($event);
$event.css("top",start+"px");
$event.css("width","94%");
$event.css("height",heightVal+"px");