1

The following is my current JavaScript code which is not working. I'm trying to change the image.

function imgchange(a)
{
    var e=document.getElementById(a);

     if(e.src == "plus.png")
     {
       e.src = "minus.png";
     }

     else
    {
      e.src="plus.png";
     }

}
5
  • 1
    How do you attach the event? Show the html Commented Mar 13, 2014 at 19:15
  • Please add the HTML and more information, like what doesn't work to your answer using the edit button. Commented Mar 13, 2014 at 19:15
  • Post your code.. In general It looks ok Commented Mar 13, 2014 at 19:17
  • Just a note, use === for type safe evaluation! Commented Mar 13, 2014 at 19:17
  • @BrentEchols src only returns a DOMString though. Commented Mar 13, 2014 at 19:43

4 Answers 4

1

When you are using img.src it returns whole path to img src, not only plus.png

You have to make comparison like http://localhost/images/plus.png (whatever your path is)

or use getAttribute method like is mentioned in undefined's post

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

Comments

1

src property includes the full url of the image, try using getAttribute method, which returns the specified value in the HTML.

if ( e.getAttribute("src") === "plus.png" )

Note that means that you should also set the new value using .setAttribute() for future comparisons. If you want to use the .src property you should either compare the full paths or use other methods like regular expression or split method:

if ( e.src.split('/').pop() === "plus.png" )

Comments

0

the function itself should be working. there must be something wrong at the place you are calling imgchange("xyz").

so maybe you can show us the code where the function is actually called.

Comments

0
function imgchange (a) {
    var e=document.getElementById(a);
    if (e.src.replace(/.+\//, '') === 'plus.png') {
        e.src = "minus.png";
    } else {
        e.src="plus.png";
    }
}

Should work.

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.