0
<img src="http://site.com/some/category/thread_17.jpg" />
<img src="http://site.com/other/thread_17.jpg" />

How to find the last image on the page, that have "thread_" after last "/" in its src attribute?

Script should throw src to some variable.

Ajax is used to find the images on external page

$.ajaxQueue({
 url: link, 
 type: 'GET',
 success: function(data) {
  var src = $('.slide img', data).attr('src');
 }
});

It gives attribute of the last image from .slide block.

Thanks.

Happy
  • 881
  • 7
  • 16
  • 32

6 Answers6

3

$('.slide img[src*=\\/thread_]:last', data) might do it

Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
1

You can iterate through ALL of the images you have & perform regex on them, like this:

$('.slide img', data).each(function(index){
   src = $(this).attr('src');
   stringarray = src.split('/');
   last_piece = stringarray[stringarray.length-1]
   regexpatt = /thread_/
   if ( regexpatt.test(last_piece) )
   {
      alert('we have a winner!');
   }
   else
   {
      alert('that was disappointing');
   }
});

I am sure there is probably a more elegant way - you should probably search through the jquery docs for it, but this works... :)

Auston
  • 480
  • 1
  • 6
  • 13
1
var src = $(data).find('.slide img').last().attr('src');
jAndy
  • 231,737
  • 57
  • 305
  • 359
1

You can use Regex in selectors

http://james.padolsey.com/javascript/regex-selector-for-jquery/

jQuery selector regular expressions

Hope this can help

Regargs.

Community
  • 1
  • 1
Shoaib Shaikh
  • 4,565
  • 1
  • 27
  • 35
1

Try the following.

var srcAttr = $('.slide img[src*=\/]', data).filter(function() {

            var src = $(this).attr('src');
            return src.substr(src.lastIndexOf("/")).indexOf('thread_') >= 0

        }).last().attr('src');

Here I am doing the following things.

  1. The selector gets us all the images with their src tags having a "/".
  2. Filtering the images that have "thread_" after the last "/"
  3. Taking the last image of all such images
  4. Taking the src attribute of it.
dotcoder
  • 2,828
  • 10
  • 34
  • 50
1

Best guess, use a little .filter() with a RegExp, and then the .last() element in the set, grab its src using .attr('src')

var src = $('.slide img', data).filter(function() {
  // only keep <img> whos src have '/thread_' without another '/' before the end
  return $(this).attr('src').match(/\/thread_[^\/]*$/);
}).last().attr('src');

jsfiddle demo

gnarf
  • 105,192
  • 25
  • 127
  • 161