0

I have been trying to use the following piece of code to change the src of an image

document.getElementById('test').src='images/test2.png';

My code looks like this. There's some CSS and other things in there but the important parts are the div and the img, and the function.

<div id='splashScreen' class='splash'>
  <button class='bigButton' onclick='introSplash()'>Hi</button>
  <img class='splashImages' src='images/splashScreen1.png'>
</div>

this is my image with a page-sized transparent button over the top of it

<script>
function introSplash() {
    document.getElementById('splashImages').src='images/splashScreen2.png';
  }
</script>

this function should be replacing the image under the button.

Pressing the button with this code returns the following error message:

Uncaught TypeError: Cannot set property 'src' of null at introSplash

all of the images are locally saved and exist with those names

I'm not sure why this is occurring, and would appreciate any help.

1
  • I see you are new... I would strongly recommend you to use JQuery to do this kind of things... bye! Commented Dec 30, 2018 at 1:03

4 Answers 4

1

You need to add the ID test to the <img> element:

<img id='test' class='splashImages' src='images/splashScreen1.png' />

Now your code will work.

The alternative, without adding any IDs, would be to use document.getElementsByClassName like so:

document.getElementsByClassName('splashImages')[0].src='images/test2.png';
Sign up to request clarification or add additional context in comments.

Comments

1

Please verify you are using document.getElementById('splashImages') but the html element has not ID. Add the id attribute

<img id="splashImages" class='splashImages' src='images/splashScreen1.png'>

Please try this and let me know how it works :)

Comments

0

You try to get the element by id, but only a class="splashImages" is given.

Comments

0

document.getElementById('splashImages') returns null because the element you want does not have the correct id. Use getElementsByClassName instead, or give it the correct id.

So you should implement one of following changes:

<script>
function introSplash() {
    document.getElementsByClassName('splashImages').src='images/splashScreen2.png';
  }
</script>

or

<div id='splashScreen' class='splash'>
  <button class='bigButton' onclick='introSplash()'>Hi</button>
  <img id='splashImages' class='splashImages' src='images/splashScreen1.png'>
</div>

3 Comments

Oh my gosh I feel silly now. Of course it wouldn't work it was a class not an ID. So sorry for wasting all of your time lol.
We've all been there :)
Yes... Everyone ve all been there expending time un a simple comma. Semicolon or id. :)

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.