An element is not written to a variable, and since there are several elements, an array must be formed, but it is formed empty.

console.log(opengal.length, opengal[0]); console.log($(".expand").length, $(".expand")[0]); console.log(zoombox.length, zoombox[0]) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> var zoombox = $("<div class='popup'></div>"); var opengal = $(".expand"); </script> <div class="expand"></div> <div class="expand"></div> <div class="expand"></div> <div class="expand"></div> <div class="expand"></div> 

opengal should be an array of 5 buttons, but for some reason it is empty.
The other variables are fine.

  • one
    make one minimal reproducible example that reproduces your mistake - Grundy
  • Sorry, I don't seem to catch the question. What exactly do you see the problem? - Duck Learns to Take Cover
  • @ Duck LEARNS, obviously, empty brackets are shown in the console, and in html all the elements are present - Grundy
  • Obviously, you have elements in the tree appear after your code has completed. Find who adds them - and drag your code there. - Pavel Mayorov
  • Do you mean to make the figcaption element static? I just added it using the script. - Eugen Eray

2 answers 2

Does $ (". expand") in the console give a different result?
@vp_arth Yes, if you enter in this way, then it correctly selects the elements.

This suggests that at the time of initialization of the opengal variable, there were no elements in the DOM yet.

Try moving the code closer to the end of the page, for example, before the closing </body> .

It may also help to take this code to the next event cycle tick:

 var opengal; setTimeout(function(){ opengal = $(".expand"); }, 0); 

However, this option does not guarantee the DOM is not required to load synchronously.

Therefore, it is best to wait for the content download event:

 document.addEventListener('DOMContentLoaded', function () { opengal = $(".expand"); }); 

For objectivity, I will give a comment from the discussion:

Obviously, you have elements in the tree appear after your code has completed. Find who adds them - and drag your code there. - Pavel Mayorov 1 hour ago

  • 2
    Thank! Really helped. Transferred a passage from a separate script down the tree in front of </ body> and it all worked. - Eugen Eray

wrap your code in window.onload, which will be called when all items have been loaded. Moving the code to the bottom of the page is a crutch that will not always work. better like this:

 <script> window.onload = function() { var zoombox = $("<div class='popup'></div>"); var opengal = $(".expand"); }; </script>