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

css, html, javascript, jquery

Solution

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 +'" />');
  }
});

Problem

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

Original source