sojutyp
sojutyp

Reputation: 316

Src attribute switch with JavaScript

I want to make a simple switch of <img src="..."> depending on the present src with JavaScript. So if the image #plus_1 is clicked, the script should check if the string 'plus' is in the src attribute, and if yes, the src attribute should change. Not sure what mistake I made, help would be very much appreciated!

JavaScript:

   function ek_ak(id) {
            var ement = document.getElementById(id);
            if (ement.img.src.includes("plus") == true) {
                ement.img.src == "minusred.png";}
        }

HTML

<img src="plusred.png" id="plus_1" onclick="ek_ak('plus_1')"/>

Upvotes: 0

Views: 64

Answers (2)

Weedoze
Weedoze

Reputation: 13943

  • You can directly send the element to the function using onclick="ek_ak(this). This will avoid the unnecessary call to retrieve the element.
  • To get the src you can simply call element.src. The element is your img
  • The call .includes(..) is returning a boolean value. You do not need to add == true.
  • You were using element.src == "minusred.png. == is used to compare elements not to assign. You should use =

function ek_ak(element) {
  console.log("Current src = " + element.src);
  if (element.src.includes("plus")) {
    element.src = "minusred.png";
    console.log("Next src = " + element.src);
  }
}
<img src="plusred.png" id="plus_1" onclick="ek_ak(this)" />

Upvotes: 1

gyre
gyre

Reputation: 16777

A few pointers:

  • ement is already a DOM element: it has no img property but you can access src on it directly;
  • Regular expressions can be used instead of String#includes;
  • You should use = as the assignment operator, instead of == (loose comparison).

function ek_ak (id) {
  var ement = document.getElementById(id);
  if (/plus/.test(ement.src)) {
    ement.src = "minusred.png"
    console.log(ement.src)
  }
}
<img src="plusred.png" id="plus_1" onclick="ek_ak('plus_1')" />

Upvotes: 1

Related Questions