jstandshigh
jstandshigh

Reputation: 109

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.

Upvotes: 2

Views: 902

Answers (3)

HenryDev
HenryDev

Reputation: 4953

You can create a container and append your divs in there. Also, it's better to use an object for multiple styles (CSS). Take a look at my solution. Hope it helps :).

$(document).ready(function() {

for (var i = 1; i <= 5; i++) {
  $('#container').append('<div class="event" ><a>Sample text</a></div>').css({
    "width":"94%",
    "color":"blue"
     });
    }

  $(".event:eq(2)").css({
    "background": "red" ,
    "color":"green",
    "width":"300px"
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="container"></div>

Upvotes: 1

JV Lobo
JV Lobo

Reputation: 6316

I think your problem comes because you're dynamically creating the elements, and them trying to apply some styles through the class selector, and this doesn't work.

I'd do in this way:

var new_element = $('<div class="event" ><a>Sample text</a></div>');
$(".container").append(new_element);
$(new_element).css('color', 'red');

Upvotes: 2

Taplar
Taplar

Reputation: 24965

$(".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");

Upvotes: 1

Related Questions