Why does the length of the array show 0 if there are 5 of them in the body?

  • 0
    <!DOCTYPE html>
      <html>
      <head>
          <title></title>
          <script>
              let liAll = document.querySelectorAll(`li`);
    
              let imgAll = document.getElementsByTagName('img');
    
    
              class Bio {
               constructor (name, lastName, subject, hobby, mark) {
                   this.name = name,
                   this.lastName = lastName,
                   this.subject = subject,
                   this.hobby = hobby,
                   this.mark = mark
                  }
              }
    
              let arrOfImg = ["imgs/one.jpg", "imgs/two.jpg", "imgs/thee.jpg", "imgs/four.jpg", "imgs/five.jpg"];
    
    
              alert(imgAll.length);
    
          </script>
          <style>
              div {
                  display: flex;
                  justify-content: space-between;
              }
              img {
                  width: 200px;
                  height: 200px;
              }
    
              .card {
                  width: 198px;
                  height: 148px;
                  display: block;
                  background: white;
                  box-shadow: 1px 1px 10px 0px grey;
                  display: flex;
                  justify-content: normal;
                  display: none;
              }
    
              li {
                  width: 110px;
              }
    
              ul {
                  list-style: none;
              }
          </style>
      </head>
      <body>
          <div>
              <img src="imgs/one.jpg" />
              <img src="imgs/two.jpg" />
              <img src="imgs/thee.jpg" />
              <img src="imgs/four.jpg" />
              <img src="imgs/five.jpg" />
          </div>
    
          
          <div class="card">
              <div>
                  <img src="imgs/one.jpg" alt="Alternate Text" />
              </div>
              <ul>
                  <li>name - Klara</li>
                  <li>last name - Gerada</li>
                  <li>subject - Medicine</li>
                  <li>hobby - learning</li>
                  <li>mark - 8.1 / 10</li>
              </ul>
          </div>
      </body>
      </html>


    JavaScript Anonymous, Jul 20, 2020

  • 2 Answers
  • 0
    Wrap all the code in the script tag in a function
    document.addEventListener("DOMContentLoaded", function () {
    // Твой код
    })
    Anonymous

  • 0
    Because the document.getElementsByTagName method didn't find anything. You cannot access an element that does not yet exist at the time the script is executed.


    Mia Stuart

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!