简体   繁体   中英

For loop append div inside div

Hi I wanted to ask the loop currently in my code I am doing this manually its working manually

          $( '<div id="demo1" > <span class="value"></span> </div><br> Loading' ).appendTo( $('.test')[0] );         
  $( '<div id="demo2"> <span class="value"></span> </div><br> Loading' ).appendTo( $('.test')[1] );         

But I am trying to do it buy function until div id demo10 this is what I tried I am trying to implement in for loop but its not working showing blank only can anyone guide me I am new to jquery I will really appreciate any advice. Thank you

  function newdiv()
{
    var j,i;
     for (i = 0; i <= 5; i++,j=i+1) {

      $( '<div id="demo-"'+j+'"' +' > <span class="value"></span> </div><br> Loading' ).appendTo( $('.test')[i] );         

     }

}

I hope the below code will solve the issue

Detail Description

  1. So when the dom loads we need to execute the function, so we invoked the function using newdiv()

  2. Now the function gets executed, so each time the i value will get incremented and it will add the new element to the div which is already in html. We select it through class name which is test.

  3. So it will append new elements to the test div

 $(document).ready(function() { function newdiv() { var j, i; for (i = 0; i <= 5; i++, j = i + 1) { var appendElement = `<div id='demo-${i}'> <span class='value'></span> </div> <br> Loading`; $('.test').append(appendElement) } } newdiv(); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='test'> hello </div>

Tryout this code, It is giving the same output as well.

 var i=0; for (i = 1; i < 11; i++) { if(i==1) $("#demo").after('<div id="demo1" > <span class="value"></span> </div><br> Loading'); else{ var div = parseInt(i)-1; $("#demo"+div).after('<div id="demo'+parseInt(i)+'" > <span class="value"></span> </div><br> Loading'); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="demo" ></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM