Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript HTML collection showing as 0 length

Tags:

javascript

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

This displays as:

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

However, when I try to get a length of eval_table, eval_table.length, it returns a value of 0. I've used this approach before, had no issues with this approach before. Is there anything wrong with what I'm trying to achieve above?

like image 941
Jack hardcastle Avatar asked May 13 '15 10:05

Jack hardcastle


People also ask

How do I find the length of a collection in HTML?

The length property returns the number of elements in an HTMLCollection. The length property is read-only. The length property is useful when you want to loop through an HTMLCollection.

What is HTML collection?

An HTMLCollection is a collection of document elements. A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number.

Which array operation can be performed on an HTML collection returned by getElementsByClassName ()?

getElementsByClassName() The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.


1 Answers

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> 
like image 182
blankmaker Avatar answered Sep 23 '22 22:09

blankmaker