3

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;
}

4 Answers 4

5

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 +'" />');
  }
});
Sign up to request clarification or add additional context in comments.

Comments

3

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);
});​​

2 Comments

You said it could make it faster. How?
The append method won't be executed each time the loop runs. It will be executed only once at the end. A couple of articles if you want to read Article 1, Article 2
2

Try:

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

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.