Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Hung Pham Viet
Hung Pham Viet
9,104 Points

Javascript code doesn't work, pls help?

I am doing a javascript code to make bulb on and off. If I use document.getElementById then my code work but if I use document.getElementsByTagName then it doesn't work. I don't quite understand why. Can anyone help me out?

My code that works:

------------------------------HTML code --------------------------------------

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Practicing Javascript</title> <link rel="stylesheet" href="main.css" type="text/css"> </head> <body> <img id="image" src="bulboff.jpg"/> <script type="text/javascript" src="myscript.js"></script> </body> </html>

----------------------------- CSS code -----------------------------------------

img { height: 250px; width: 200px; }

------------------------ JAVASCRIPT code -----------------------------------

var imgHolder = document.getElementById("image");

var lighton = function() { this.src = "bulbon.jpg"; }

var lightoff = function() { this.src = "bulboff.jpg"; }

imgHolder.onmousedown = lighton;

imgHolder.onmouseup = lightoff;

BUT IF I CHANGE Javascript code as var imgHolder = document.getElementsByTagName("img"), it doesn't work again???

HELP HELP pls?

Hung Pham Viet
Hung Pham Viet
9,104 Points

Thanks but the default of Javascript is getElementsByTagName. Must have "s" after "Element".

2 Answers

Try this?

------------------------ JAVASCRIPT code -----------------------------------

var imgHolder = document.getElementById("image");

var lighton = function() { imgHolder.src = "bulbon.jpg"; }

var lightoff = function() { imgHolder.src = "bulboff.jpg"; }

imgHolder.onmousedown = lighton;

imgHolder.onmouseup = lightoff;

Hung Pham Viet
Hung Pham Viet
9,104 Points

Thank you Rick. Your code works of course.

My concern is how can I use "getElementsByTagName" to make this code also works as well?

I am just learning Javascript few days so I really want to attack a problem with multiple solutions.