Javascript HTML collection showing as 0 length
In order to access the element at position 0 of HTMLCollection you should use
setTimeout(() => {
let elms = document.getElementsByClassName('ClassName').item(0)
}, 0);
Using setTimeout
to make sure DOM is finished render.
You could write the code inside the
$('document').ready(function(){
// your code
});
or on body onload or on DOM ready
<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 have tried in this jsFiddle
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:
- Add the self-executing
<script>
as the last thing in your<body>
tag or; - 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 })
- jQuery's
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>