View Full Version : replace class of element with anchor click

01-04-2007, 01:18 AM
the title pretty much sums it up I guess. I hope this is in the right place.

Anyhow, what I want is a link with an onClick attribute that changes the class attribute of an element on the page, using some kind of javascript function. Now, I'm new at javascript, so I can't really write one on my own, so if anyone can help and point me in the right direction or give me some samle code or something, that would be cool.

I've been searching online for a while now, so I am about to give up.

But here is an example of what I was talking about, if you need html for reference or something...

<a href="#" onclick="whateverthefunctionis"><img src="someimage" alt="someimage" class="small" /></a>
<p><a href="#" onclick="whateverthefunctionis">clicking here changes the class</a></p>when you click the image when it is 'small', it changes it to 'orig'. when you click it when it is 'orig' it changes it to 'small'.

I hope someone can help. It's probably real simple but I can't figure it out.

01-04-2007, 02:01 AM
Try something like this:

<script type="text/javascript">
function toggle(elemId) {
imgElem = document.getElementById(elemId);
imgElem.className = (imgElem.className == 'small') ? 'orig' : 'small';

<img id="myimage" src="zebra.jpg" alt="someimage" class="small" onclick="toggle('myimage')"/>
<span onclick="toggle('myimage')">toggle the class</span>

01-04-2007, 02:09 AM
thanks! that helped a lot! :D