1

So I am trying to change the source of my HTML image element. I used document.getElementId('image') to change it but my code is not working and I get no errors. If i erase that line of code the sign variable works and the sign shows up in my site.

HTML CODE:

    <img src="images/zodiac.jpg" alt="Chinese Zodiac">

Javascript CODE:

    document.getElementById("images/zodiac.jpg").src = image; 
1
  • document.getElementById("images/zodiac.jpg").src = image; here u made mistake .. Commented Sep 12, 2014 at 4:28

3 Answers 3

2

Add an id to the image :

<img id="zodiac" src="images/zodiac.jpg" alt="Chinese Zodiac">

Replace

document.getElementById("images/zodiac.jpg").src = image; 

by

document.getElementById("zodiac").src = image; 
Sign up to request clarification or add additional context in comments.

1 Comment

YOU THE MAN! worked like a charm. Its weird cause everything looked up online said nothing about img id.
0

your method of using the document.getElementById() is wrong. you are supposed to pass the ID of the img tag and you are passing the value of the src. Instead of this, give an ID to the img tag

<img src="images/zodiac.jpg" id="zodiac" alt="Chinese Zodiac">

and in javascript:

document.getElementById('zodiac');

So your final syntax should be

document.getElementById("zodiac").src = image;

getElementById will get you the reference of the img object and from that it will pick the src property and assign the image variable to it.

Hope this helps!

Comments

0

Looks like you are trying to access an element by its id without giving it an id. Consider giving it an id or some sort of uniqueness. It can be done by giving it

  • an id

<img id="zodiac" src="images/zodiac.jpg" alt="Chinese Zodiac">

Then

document.getElementById("images/zodiac.jpg").src = image;

  • a name

<img name="zodiac" src="images/zodiac.jpg" alt="Chinese Zodiac">

Then

document.getElementsByName("zodiac").src = image;

  • a class

<img class="zodiac" src="images/zodiac.jpg" alt="Chinese Zodiac">

Then

document.getElementByClassName("zodiac").src = image;




Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.