0

I want to code that when I click on a image the src of this image changes to another src. But it doesn't work. Can someone help me?

<?php require_once("php/config.php"); ?>
<!DOCTYPE html>
<html>
<head>
<title> test </title>
<script type="text/javascript" src="javascript/liabary.js"></script>
</head>
    <body>
        <img id="img" onclick="next()" src="img/bildergalerie/bild3.jpg" id="b3" width="1000" height="500" alt="image" />
        <script type="text/javascript">

        function next() {
            var img = document.getElementByIdName("img");
            img.src = "image2.jpg";     
        }
        </script>
    </body>
</html>
Steffen Moritz
  • 7,277
  • 11
  • 36
  • 55
Lupos
  • 896
  • 12
  • 40

2 Answers2

2

getElementsByClassName returns an array-like object, so you need to refer to the specific one you want. For example img[0].src = "image2.jpg";

jsFiddle example

Or, instead of looking for the class, you can use the id instead:

var img = document.querySelector("#b3");

or

var img = document.getElementById("b3");

This will only return one element, which then you can reference in the way you did.

j08691
  • 204,283
  • 31
  • 260
  • 272
2

Since you have an ID attached to your image I suggest you to use getElementById() which only returns a single element instead of a collection.

function next() {
  var img = document.getElementById("myImg");
  img.src = "http://noticias.universia.com.br/net/images/consejos-profesionales/m/mo/mot/motivos-influenciar-mudar-imagem-profissional-noticias.jpg";
}
<img class="img" id="myImg" onclick="next()" src="http://www.apicius.es/wp-content/uploads/2012/07/IMG-20120714-009211.jpg" id="b3" width="300" height="150" alt="image" />
Christoph
  • 50,121
  • 21
  • 99
  • 128
Mathiasfc
  • 1,627
  • 1
  • 16
  • 24