Consider this code:
function changeImage()
{
var image = document.getElementById('myImage');
if (image.src.match("bulbon"))
{
image.src = "pic_bulboff.gif";
}
else
{
image.src = "pic_bulbon.gif";
}
}
I do not understand why this stores the result of getElementById()
to a variable that is then used in the if
statement as we can access the attribute src
by simply using getElementById()
everytime, like so:
function changeImage()
{
if(document.getElementById("myImage").src=="pic_bulboff.gif")
{
document.getElementById("myImage").src="pic_bulbon.gif";
}
else
{
document.getElementById("myImage").src="pic_bulboff.gif";
}
}
Why use a variable instead of using getElementById()
repeatedly ?