You have several things going on that explains this behaviour:
You are performing the console.log at a moment that there are no such elements yet in the document. Probably the JavaScript executes before the document is ready. This explains why temp[0] is undefined.
The HTMLCollection returned by getElementsByClassName is not an array and has some magical behaviour: it is a live collection. So if the document gets an additional element of that class, it will magically appear in that temp collection without you touching it!
When you log an object to console, the Chrome dev tools will not collect all the object properties at that moment, but asynchronously. This means that although at the time of logging the collection was empty, it no longer is when you click on the dev tools to see what is in the collection.
See the first two points illustrated in this script:
var temp = document.getElementsByClassName('html5gallery-tn-image-0');
console.log(temp.length); // 0
// add the class to the element
mydiv.className = "html5gallery-tn-image-0";
console.log(temp.length); // 1
<div id="mydiv"></div>
Solution
Move your JavaScript code so that it only executes when the document is completely loaded. Either:
- Move your Javascript to the end of the
body tag, or
- wrap the code in a
document.addEventListener('DOMContentLoaded', function () { ... }); callback.
document.getElementsByClassName('html5gallery-tn-image-0')[0]and let me know what you get.