Frustrating issue with JavaScript's getElementById()
-
22-09-2019 - |
Question
This is the gallery I've been asked to implement
http://sandbox.leigeber.com/slideshow/
I've chopped and changed it ever so slightly so it'd fit into the new site's templating system a bit easier.
Whenever I run it, this line causes an error
ta=document.getElementById(thumbid);
Saying that ta
is null. I know the thumbid var's value does exist as an Id of the unordered list.
I've tried to figure what's been going on for at least half an hour now, and can't seem to nail it!
Can someone please tell me what I'm doing wrong?
Solution
Yeah the code looks fine, and running the same lines from Firebug console work OK, so it makes me wonder if the thumbs
element actually exists at the time of running? Is it in a document.ready
-style handler? If it's being called before the element exists on that page, then ta
will be null, which would create that error.
OTHER TIPS
It looks like the slideshow function is called for initialization too early. This will be called before the DOM tree is ready:
var slideshow = function() {
...
} ();
try removing that () at the end.
Good news! jQuery is written in vanilla Javascript! You should be able to copy out their method for getting elements by ID and use that.
It's a little unclear what value thumbid
should have, but it looks to me like your problem is that the li items in your unordered list don't have id
s, they have value
s.
Calling document.getElementById('thumbs')
works fine to get the ul
element of the list itself.
In Safari 4 line 19 was throwing me a type error regarding ta
which was null
.
This is due to the line you pointed out where ta
was assigned.
I like how you encapsulate the functions in a closure, but I think the window.onload
can be changed to be more jQuery like; the same can be said of actually selecting the elements you're looking for, something like t=$('ul#thumbs li')
should do the trick. I don't know if throwing a var
in front of ta
is going to fix anything, but it's worth a shot.