For loop syntax in Javascript

- 1 answer

Ad

I am trying to create a loop to show 5 images using Javascript. I am having some trouble understanding the syntax.

This is what I have so far.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
      <title>Challenge: Daisy chain</title>
  </head>
  <body>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
    <script>
        var image = $("<img>")
        .attr('src', 'https://upload.wikimedia.org/wikipedia/commons/2/29/English_Daisy_(Bellis_Perennis).jpg')
        .attr('width', '10')
        .attr('alt', 'new name')
        .appendTo('body');

        for(i = 0, i < 5, i++) {
            $(image).appendTo('body');    
        }
    </script>
  </body>
</html>
Ad

Answer

Ad

You have to actually create the images inside the loop to get five images, otherwise you only get one image, that you append five times, but it's still just one single image

for(i = 0; i < 5; i++){
    $("<img />", {
        src   : 'https://upload.wikimedia.org/wikipedia/commons/2/29/English_Daisy_(Bellis_Perennis).jpg',
        width : 10,
        alt   : 'new name'
    }).appendTo('body');
}

Also note that jQuery can take the attributes/properties directly when constructing elements

Ad
source: stackoverflow.com
Ad