Take the 2-minute tour ×

I've the following code: (a fiddle is here)

<img class="changeable" src="http://placehold.it/100x120&text=anniversary">
    <ul class="rollover_list">
        <li><a href="#" rel="http://placehold.it/100x120&text=anniversary"><span class="orange">> </span>Anniversary</a></li>
        <li><a href="#" rel="http://placehold.it/100x120&text=birthday"><span class="orange">> </span>Birthday</a></li>
        <li><a href="#" rel="http://placehold.it/100x120&text=christmas"><span class="orange">> </span>Christmas</a></li>
        <li><a href="#" rel="http://placehold.it/100x120&text=wedding"><span class="orange">> </span>Wedding</a></li>

and I'm attempting to change the src attribute of the image based on the rel value of the anchor.

I'm trying this jquery -

$("ul.rollover_list li a").hover(function() {
            var $link = $(this).attr('rel');
            var $target = $(this).closest('img.changeable');
            $($target).attr('src', $link);

as I need to use it multiple times on a page.

Am I right in thinking that .closest() will locate the nearest matching element by traversing up the DOM?

Don't know what I'm missing but it ain't happy.

share|improve this question
$target is already a jQuery object, you don't need to jQuerize it again with $($target). Apart from that, what's exactly your problem? What makes you unhappy? –  Álvaro G. Vicario Oct 25 '11 at 16:28

2 Answers 2

up vote 4 down vote accepted

You have 2 problems in your jQuery:

  1. jQuery's closest() method only works in trees, in other words: it will only work if the wanted result is a parent of the current element.
  2. $($target). $target is already an element, you can't select an element using an element as a selector, for that you'd need a method like find however, this isn't what you were trying to do.


share|improve this answer
Nicely done Korvin –  William Walseth Oct 25 '11 at 16:25
This is exactly what I'm trying to do, but I'm going to have lots of these on a page so I'd like a version that will just find the img.changeable that's nearest the ul. Would you have any suggestions as to how I might do that? Any advice is appreciated! –  Cordial Oct 25 '11 at 19:59
if it's always ordered like that, it's easy: $(this).closest('ul').prev() : jsfiddle.net/U7SNz/3 –  Korvin Szanto Oct 25 '11 at 20:19
This is perfect - thank you! –  Cordial Oct 26 '11 at 8:16

That line that appears as...


should probably be...

$target.attr('src', $link);
share|improve this answer
This doesn't fully solve the problem, there's still an issue with the jquery.closest method she's using. –  Korvin Szanto Oct 25 '11 at 16:21

Your Answer


