1

I have the following html:

<li>
   <a href=\"p://emotion/appreciate\" onclick=\"flip()\">
        <img src=\"smile.png\" />
   </a>
</li>

Basically, I want the flip function to replace the src of the img enclosed in it to smile-inactive when pressed, and change it back again to smile.png if it's now already in smile-inactive.png. How can I do this without having to do document.getElementById if I don't want to give the img an id?

2
  • This is a task that a framework like jQuery can really help with. Will save you a lot of time and head ache with browser compatibility. Commented Feb 16, 2012 at 22:26
  • 1
    Why not give the image an ID? Commented Feb 16, 2012 at 22:26

2 Answers 2

2

Inside your flip function, I would make sure that this points to the anchor you just clicked, then grab the img as the first childNode:

<a href=\"p://emotion/appreciate\" onclick=\"flip.call(this)\">

function flip(){
    var img = this.children[0];
    if (/smile\.png/.test(img.src))
        img.src = "smile-inactive.png";
    else
        img.src = "smile.png"
}

EDIT

As @am not i am points out, you can achieve a slight gain in browser support by switching

var img = this.children[0];

to

var img = this.getElementsByTagName("img")[0];
Sign up to request clarification or add additional context in comments.

5 Comments

Ah, you fixed both corrections I was going to suggest. +1 but to be just a wee bit more correct, I'd escape the . in the regex. Should't make an actual difference though.
@amnotiam - indeed - escaped. Yeah, I forgot childNodes gives you text nodes too, while children only gives you the "good stuff" :) -- I'm not the dom ninja you are!
I'm not a DOM ninja... I just play one on StackOverflow. That said, you could pick up a little more browser support with getElementsByTagName instead of children, but really you're only gaining FF3, so who cares.
...love that you use .call() BTW.
@amnotiam - yeah, we've had that conversation - passing this as a param is soooooo cheesy. BTW - congrats on the rep - looks like we'll be welcoming you into the 10K club here pretty soon
0

Take both images, merge them to one, and just use offset to determine which one is shown.
You can do it by simply by CSS.

3 Comments

CSS won't help with click events though. If we were talking about a :hover, I'd totally agree.
I know what you mean, and I agree as well, Just wanted to prevent to load of two different images.
Yeah, it's still a good idea. Would just need a little JS to swap a class.

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.