Javascript HTML collection displaying length 0

var eval_table = document.getElementsByClassName("evaluation_table"); console.log(eval_table); 

This is displayed as:

 [item: function, namedItem: function]0: table.widefat.fixed.evaluation_table length: 1 __proto__: HTMLCollection 

However, when I try to get the length of eval_table , eval_table.length , it returns 0 . I used to use this approach, before I had no problems with this approach. Is there something wrong with what I'm trying to achieve above?

+14
source share
3 answers

This is because your JS is running before the elements are passed to the DOM. I am sure that the script you have started loading to <body> your html. You have two options:

  • Add self-executing <script> as the last in the <body> or tag;
  • Wrap your function so that it waits for the DOM to load before executing. You can do this with:
    • jQuery $(document).ready or
    • If you are not using jQuery: document.addEventListener("DOMContentLoaded", function(e) {// do stuff })

Sample code 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> 
+32
source

You can write the code inside

 $('document').ready(function(){ // your code }); 

either when loading the body or in the readiness of the DOM

 <body> Your HTML here <script> // self executing function here (function() { var eval_table = document.getElementsByClassName("evaluation_table"); console.log(eval_table,eval_table.length); })(); </script> </body> 

I tried in this jsFiddle

0
source

To access an element at position 0 of the HTMLCollection you must use

  setTimeout(() => { let elms = document.getElementsByClassName('ClassName').item(0) }, 0); 

Use setTimeout to verify that the DOM has finished rendering.

0
source

All Articles