0

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')"/>
3
  • 1
    Hint : = vs == Commented Mar 3, 2017 at 7:43
  • 3
    ement.img.src = "minusred.png" Commented Mar 3, 2017 at 7:44
  • and includes function not supported by IE. Commented Mar 3, 2017 at 7:45

2 Answers 2

1

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')" />

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

Comments

1
  • 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)" />

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.