Reputation: 1774
So I am making a slideshow plugin for jquery/javascript, and I am currently trying to create a list of all elements with the class name "slideshow". To do this, I define a global variable at the top of the javascript module that calls a function that (should) return the list of elements with the class name "slideshow". Though, for some reason, it returns an empty array, inside the function and out, even though there is clearly a div with a class name "slideshow", except when I print the global variable defined at the top of the module inside a separate function (not the one previously mentioned) it works without a flaw.
Here is the html:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="slideshow.js"></script>
</head>
<body>
<div class="slideshow"></div>
</body>
Here is the javascript/jquery module "slideshow.js":
var slideshows = getSlideshows();
function getSlideshows() {
var slideshows = document.getElementsByClassName("slideshow");
console.log(slideshows); // prints []
return slideshows;
}
console.log(slideshows); // prints []
$(function test1() {
console.log(slideshows); // prints [div.slideshow], which is correct.
});
Any idea why it is printing different values?
Thanks!
Upvotes: 1
Views: 60
Reputation: 2613
Scripts in the <head>
section execute before the body of the page is parsed, so the HTMLCollection
that is returned by getElementsByClassName
is empty when you display it the first two times.
As soon as the document is fully loaded, test1
runs and the element shows up. That's because HTMLCollection
is live : it is automatically updated as the DOM changes.
Upvotes: 1
Reputation: 4634
You have two options, either you can put your script in the footer or wrap your script and tell it to fire when the document is ready:
$( document ).ready(function() {
var slideshows = getSlideshows();
function getSlideshows() {
var slideshows = document.getElementsByClassName("slideshow");
console.log(slideshows);
return slideshows;
}
console.log(slideshows);
}
Otherwise, your script is firing before the html it's trying to reference exists.
Upvotes: 1