javascript for loop issue

Issue I am having is as follows: This for loop should be putting a number in the address and counting up to 152 and then putting it full address as follows

<img src="http://pokeapi.co/media/img/1.png">
<img src="http://pokeapi.co/media/img/2.png">

and so on. What am I missing?

var webaddress = ['<img src="http://pokeapi.co/media/img/">'];
var text = "";
var i;
for (i = 0; i < 152; i++) {
  text += webaddress[i] + ".png";
}
document.getElementById("Pokeman").innerHTML = text;
<!DOCTYPE html>
<html>

<head>
  <title></title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="style.css">
  </style>
  <script type="text/javascript" rel="script" type="script" href="script.jss"></script>
  <script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script>

</head>


<body>
  <div id="container">

    <p id="Pokeman"></p>



  </div>

</body>

</html>

Answers 1

  • You are setting your javascript in the head - but the element that is referenced (#Pokeman) is not in the DOM yet - simply move the js block to the end - before the closing body tag. and since you are using jquery - i simplified the js and used it too.

    EDIT - I just inserted your img code into the function so that it will render the images as the number increments.

    <!DOCTYPE html>
    <html>
      <head>
        <title></title>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="style.css"/>
    
      </head>
      <body>
        <div id="container">
          <p id="Pokeman"></p>
        </div>
        
      <script type="text/javascript" rel="script" type="script" href="script.jss"></script>
      <script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script> 
      <script>
        $(document).ready(function(){
        for (var i = 1; i <= 152; i++) {
           $("#Pokeman").append('<img src="http://pokeapi.co/media/img/'+ i + '.png"/>');
         }
       })
     </script>
      </body>
    </html>


Related Articles