Newbie in javascript.. Need a little help.
I have a SPAN or IMG that I want to fadeOut using javascript. However nothing happens when I do this:
// HTML
<span id='test_one'>Span Text Here</span>
<img src='img_src_here' id='test_two'>
// JavaScript
$(test_one).fadeOut();
$(test_two).fadeOut();
But if I do this, it functions correctly:
// HTML
<div id='test_one'>Span Text Here</div>
// JavaScript
$(test_one).fadeOut();
Am I just making or a silly mistake or am I going insane?
Thanks
Coulton
Assuming you’re using jQuery, your selector is incorrect:
Note that it should be a string (so single or double quotes) and use ‘#’ to select by id. Documentation of selectors can be found on the jQuery site.
This should work:
Edit
As to why it works with the
divbut not theimgorspan, I’m not entirely clear but as @Steve pointed out, it is possible to reference elements by using theirids as global variables. However, this is non-standard behaviour and only some browsers (notoriously IE) perform this mapping of elementids to the global namespace. IE also allows fetching of named elements viagetElementById()! See this and this. I would suggest not depending on this behaviour.