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?
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.
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.
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.
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:
<script>
as the last thing in your <body>
tag or; $(document).ready
or 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With