Skip to content
Advertisement

myFunction querySelector, blank page

I have 50 more images to put on my html page so I use this code thanks to your help before and it’s working.

function myFunction() {
      for(let id=1; id<=50; id++){
        document.querySelector('#images').innerHTML += `<img class="img-responsive" src="images/image${String(id).padStart(2, '0')}.jpg" />`
      }
    }

But I need to change this code to this :

function myFunction() {
      for(let id=1; id<=50; id++){
        document.querySelector('#images').innerHTML += `
<div class='col-sm-4 more crop col-xs-6 col-md-3 col-lg-3'>
<a class="thumbnail fancybox" rel="ligthbox" href="images/image${String(id).padStart(2, '0')}.jpg">
<img class="img-responsive" alt="" src="images/image${String(id).padStart(2, '0')}.jpg" />
</a>
</div>`
      }
    }

and when I do this, I see it working in my inspector but I have a blank page and there is no error in the console.

Does anyone know why ? Did I miss something ?

Advertisement

Answer

Look in the console for errors (F12)

Also you are hammering the DOM

Try this instead

<!doctype html>
<html>

<head>
  <title>Load images</title>
  <script>
    function myFunction(numImages) {
      const html = Array.from(Array(numImages).keys()).slice(1).map(key => {
        const id = String(key).padStart(2, '0');
        return `<div class='col-sm-4 more crop col-xs-6 col-md-3 col-lg-3'>
    <a class="thumbnail fancybox" rel="ligthbox" href="images/image${id}.jpg">
      <img class="img-responsive" alt="" src="images/image${id}.jpg" title="Here would be image${id}" />Here would be img ${id}
    </a>
  </div>`
      })
      document.querySelector('#images').innerHTML = html.join("");
    }

    window.addEventListener("load", function() {
      myFunction(5); /* change to 50 when you are happy */
    });

  </script>
</head>

<body>
  <div id="images"></div>
</body>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement