Home > Back-end >  Cannot select the index of the div
Cannot select the index of the div

Time:08-25

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      .img {
        display: none;
      }
    </style>
    <title>Document</title>
  </head>
  <body>
    <div >
      <img src="/images (1).jpg" alt="" />
      <img src="/images (3).jpg" alt="" />
    </div>
    <script>
      var img = document.getElementsByClassName("img");
      for (i of img) {
        i[0].style.display = "block";
      }
    </script>
  </body>
</html>

when trying to select the index of the div using brackets I always end up with

Uncaught TypeError: Cannot read properties of undefined (reading 'style') at html.html:22:14 (anonymous) @ html.html:22

CodePudding user response:

Just make a little change on your for loop. For all div of class img you can write this

for (let i of img) {
    i.style.display = "block";
 }

And for only first div -

 img[0].style.display = "block";

CodePudding user response:

Maybe you can try to use .querySelectorAll("img"); instead of .getElementsByClassName("img").

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

  • Related