Игор Рајачић Игор Рајачић - 4 months ago 31x
Javascript Question

jQuery create DIV with dynamic ID and defined CSS attributes (which define look and position of that div)

I have some basic code here. It just creates a div element to a certain defined position, and the ID is not dynamic.

var i=1;
while (i<=6)
jQuery('<div/>', {
id: 'karta_back'
// I don't know how to insert CSS here


The problem is with dynamic ids. With css, I don't know how to define the CSS inside that function. For this example, I used the internal CSS that is defined somewhere in the document. With the position, I suppose that cards need to be CSS absolute positioned to perform like i would like.

This is the result that I have with this simple code I wrote:

This is what i want to achieve:

How can I do this?


If I understand you correctly just, use the style attribute, you don't need a dynamic id:

var i = 1;
while (i <= 6) {
    jQuery('<div/>', {
        id: 'karta_back' + i, //this will add serial number to end of ID
        //this is a good starting point for what you're trying to accomplish
        style: 'position:absolute;margin-left:' + i * 20 + 'px;z-index:' + i;


So you can select them like:

$('#karta_back1', '#karta_back2'); //selects first two

Here is a jsFiddle example of it working, with a crappy card image.