Javascript HTML collection showing as 0 length

This is because your JS is running before the elements are rendered to the DOM. I bet the script you have running is loaded before the <body> of your html. You have two options:

  1. Add the self-executing <script> as the last thing in your <body> tag or;
  2. Wrap your function so that it waits for the DOM to be loaded before executing. You can do this with either:
    • jQuery’s $(document).ready or
    • if you’re not running jQuery: document.addEventListener("DOMContentLoaded", function(e) {// do stuff })

Code sample below:

<html>
  <head></head>
  <script>
    document.addEventListener("DOMContentLoaded", function(e) {
      var eval_table = document.getElementsByClassName('evaluation_table');
      console.log(eval_table, eval_table.length);
    });
  </script>
  <body>
    <div class="evaluation_table"></div>
    <div class="evaluation_table"></div>
    <div class="evaluation_table"></div>
    <div class="evaluation_table"></div>
  </body>
</html>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)