1

When clicking on an image, the image source should change, as well as the class of the matching span.

HTML:

<span class="oldClass">
    Some Text
    <img id="IdForThisImg" onclick="changeImage('IdForThisImg')" src="imgOld.png">
</span>
<span class="oldClass">
    Some Text 
    <img id="IdForAnotherImg" onclick="changeImage('IdForAnotherImg')" src="imgOld.png">
</span>

I have tried numerous attempts for changing the class name with inspiration from "Adding and Removing Classes, with simple cross-browser JavaScript".

Javascript:

function changeImage(id)
{
    element=document.getElementById(id)
    if (element.src.match("imgOld"))
    {
        element.src="imgNew.png";
        document.getElementByClassName("oldClass").className = "newClass";
    }
    else
    {
        element.src="imgOld.png";
        document.getElementByClassName("newClass").className = "oldClass";
    }
}

My problem appears to be that I am not getting the element that i want to change the class name of. Changing the image works perfectly, but I cannot change the class name.

Is it correct that the class name is not changing because I am not getting the correct element, if not could you point me in the direction of what it is? If it is correct, why is my current solution not working?

Additional info: I am using bootstrap twitter, using a , which I would like to change to "badge badge-default" when the image changes.

Community
  • 1
  • 1
Emil Nielsen
  • 195
  • 4
  • 15

2 Answers2

0

There is no getElementByClassName method. The correct method is getElementsByClassNames, note the plural Elements.

That's an understandable confusion, given the fact that the more common one is getElementById. The reason why of this difference is that, contrary to id, a class can refer to multiple elements.

Also, this method will — understandably — return an array, which means that you can't run your className method without iterating the elements.

Sunyatasattva
  • 5,619
  • 3
  • 27
  • 37
  • Thank you very much, I simply added an id to the span and used that instead of the class to get the element, and the change the class name. It might not be the simplest way but it worked. – Emil Nielsen Mar 19 '13 at 13:07
  • If you have more than one `span` as per your example, it *might* work, but **please don't break the internets!** You can't have multiple elements with the same `id` on the same page. – Sunyatasattva Mar 19 '13 at 13:10
0

You need to make a reference to the parent node, like this:

function changeImage(id)
{
//Element
var element=document.getElementById(id);
//And parent node
var parent = document.getElementById(id).parentNode;
if (element.src.match("imgOld"))
{
    element.src="imgNew.png";
    parent.className = "newClass";
}
else
{
    element.src="imgOld.png";
    parent.className = "oldClass";
}

}

Ihor Patychenko
  • 196
  • 6
  • 19