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>
</ul>
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.
You have 2 problems in your jQuery:
closest()method only works in trees, in other words: it will only work if the wanted result is a parent of the current element.$($target).$targetis already an element, you can’t select an element using an element as a selector, for that you’d need a method likefindhowever, this isn’t what you were trying to do.http://jsfiddle.net/U7SNz/2/