Paul
Paul

Reputation: 142

Create divs using a for loop in jQuery and assign IDs to each div

I am currently creating divs using a for loop.

The problem is when I try to assign a unique id to every div element that is being created within the for loop.

I am getting closer but at the moment the count starts at 36 instead of being 1.

Thanks so much for you help!

Here is my html:

<!DOCTYPE html>
<html>
<head>
<title>Intro Webpage!</title>

<meta charset="UTF-8" /> 
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0; target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
</body>
</html>

Now, this is my script.js:

for(i = 0; i < 35; i++) {
$(document).ready(function(){
    $('body').append('<div id="div'+ (i++) +'" />');
});
}

Also, my css:

div {
width: 167px;
height: 167px;
border-radius: 10px;
background-color: #ff0000;
display: inline-block;
margin-left: 5px;
}

Upvotes: 3

Views: 29334

Answers (4)

Akhil Sekharan
Akhil Sekharan

Reputation: 12693

Try:

$(document).ready(function(){
    var html='';
    for(i = 0; i < 35; i++) {
        html += '<div id="div'+ i +'" />';
    }
    $('body').append(html);
});

Upvotes: 2

Sang Suantak
Sang Suantak

Reputation: 5265

All the provided answers will do the job but if you want to make it faster, you can do it like this. Also, if you want the div id to start with 1, you should do ++i instead of i++. i++ doesn't make sense since that's being done by the for loop automatically.

$(document).ready(function() {
    var divsToAppend = "";
    for (i = 0; i < 35; i++) {
        divsToAppend += '<div id="div' + (++i) + '" />';        
    }
    $('body').append(divsToAppend);
});​​

Upvotes: 3

Joe Mills
Joe Mills

Reputation: 1619

Take the $(document).ready out of the loop for starters.

$(document).ready(function() {
    // do loop here
}    

Upvotes: 1

Adil
Adil

Reputation: 148150

You need to put loop in side document.ready instead of putting document.ready in loop also you may not need to increament i within loop body as it is increamented in loop signature. You can read more about document.ready here

$(document).ready(function(){
  for(i = 0; i < 35; i++) {
    $('body').append('<div id="div'+ i +'" />');
  }
});

Upvotes: 5

Related Questions