0

I want to change a image after my page is loaded. I wrote a Java Script file but I don't know where my error is.. I also don't get an error in the console...

JavaScript:

function changeImage(){ changeImage = document.getElementsByClass("carousel-indicators"); changeImage = changeImage.getElementsByTagName("img")[0].src; actualImage = document.getElementsByClass("item active"); actualImage = actualImage.getElementsByClass("img-wrapper-inner"); actualImage.getElementsByTagName("img").src = changeImage; } 

I also call the function with:

<img onload="changeImage()"> 

Greetings and Thank You!

7
  • For one thing, it's document.getElementsByClassName, not getElementsByClass Commented Feb 27, 2017 at 20:30
  • What do you mean? Commented Feb 27, 2017 at 20:30
  • 1
    I'm guessing that your changeImage function isn't being called. If you put a console.log in it, does it show up in the console? Commented Feb 27, 2017 at 20:31
  • 1
    @qxz means that the method Document.getElementsByClass does not exist. You can find the documentation on Document.getElementsByClassName on mdn: developer.mozilla.org/en/docs/Web/API/Document/… Commented Feb 27, 2017 at 20:33
  • I just typed into my changeImage() function now alert("Worked!"); - But I do not get a alert... So at least my function isn't called... But why? I say <img onload="changeImage()"> Commented Feb 27, 2017 at 20:35

1 Answer 1

2

As qxz pointed out you're probably looking for the Document.getElementsByClassName method.

Furthermore using the same variable name as your method name and not using var to declare new variable may lead to unexpected results. As JavaScript has no problem in overriding your scope.

Last but not least, getElementsByClassName returns an array. Not a single HTMLElement. You should retrieve an element from the array to manipulate. Instead of trying to change the src field of the array.

So combining these items would give you some code like:

function handleImageLoad() { var loadedImage = document.getElementsByClassName('loadableImage')[0].src; document .getElementsByClassName('loadState')[0] .innerHTML = 'Loaded image: ' + loadedImage; }
<img class="loadableImage" src="http://lorempixel.com/200/200" onload="handleImageLoad()" /> <p class="loadState">Loading...</p>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.