1

I have the following HTMl structure, which i cannot change.

<div class="X">
    <ul>
        <li><a><img></a></li>
        <li><a><img></a></li>
        <li><a><img></a></li>
        <li><a><img></a></li>
        <li><a><img></a></li>
        <li><a><img></a></li>
        <li><a><img></a></li>
        <li><a><img></a></li>
        <li><a><img></a></li>
        <li><a><img></a></li>
    </ul>
</div>

The number of li items varies. I would like to select the nth element from the back and modify the img src.

This is what i have so far:

$('div.X').find('img').css('background-color', 'red');

I need some way to loop over the results of the .find and then somehow select the nth last element. I was thinking i should somehow reverse the list so i could just use the nth-child() selector.

I've found various other nth related questions, but i havn't been able to figure out how to nail this.

Any help is much appriciated.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Splurk
  • 711
  • 1
  • 5
  • 15
  • Is the `nth` one different every time? Or is it always the `last - 1` or `last - 2`, etc...? – andyb Sep 12 '12 at 09:00
  • In my case it's actually the last -1, but figured i would write nth to make it easier for others to find and use. – Splurk Sep 12 '12 at 12:23
  • Ok, now that the question is clearer, you could just use `$('.X li:nth-last-child(2) img').attr('src', 'newSrc');​` :-) – andyb Sep 12 '12 at 12:34
  • @andyb: Be careful: [`:nth-last-child()` is not supported by jQuery](http://stackoverflow.com/questions/11745274/what-css3-selectors-does-jquery-really-support-e-g-nth-last-child), despite being a CSS selector. If it works it's only because the browser supports it natively. – BoltClock Sep 12 '12 at 20:51

2 Answers2

0
$('div.X img:eq(' + ($('div.X img').length - n) + ')')

Where n is how many back you want.

Note I used :eq() not :nth-child() - they are not the same.

Note2: There may be an off-by-one error here, so be sure to test it.

Ariel
  • 25,995
  • 5
  • 59
  • 69
0

Here you go... http://jsfiddle.net/bYaRx/

I might have gone a little overboard with the implementation. I'm bored at work. Here's the relevant jQuery to get the correct img tag:

var $img = $('.X img');
$img.filter(':eq('+($img .length - (n+1))+')');
gislikonrad
  • 3,401
  • 2
  • 22
  • 24
  • Awesome solution, works great. I didnt know the :eq selector. I ended using .eq() function, as it allows for using negative values. $('div.X').find('img').eq(-2).attr('src', newImg); Thanks alot for your quick and thorough help! Much appriciated, would have taken me forever :-) – Splurk Sep 12 '12 at 12:25