1

I have the following loop :

$('.sampleAddress li span').filter(function() {
    var currentLine = $.trim($(this).html().replace(/ /g, '')).toUpperCase();
    var unmatched = $.trim(unmatchedLine.replace(/ /g, '').toUpperCase().replace("&", "&"));
    if (currentLine.indexOf(unmatched) !== -1) {
        $(this).html($(this).text().replace("  ", " ").replace("&", "&AMP;").replace(unmatchedLine.toUpperCase(), '<span class="matchedClass">' + unmatchedLine.toUpperCase() + '</span>'));
    }
});

I am just wondering how I could traverse this list in reverse order and exit the loop within the if statement ?

Kevin Brechbühl
  • 4,717
  • 3
  • 24
  • 47
StevieB
  • 6,263
  • 38
  • 108
  • 193
  • It looks like `.filter` is the wrong method for what you are trying to do. You are probably looking for `.each`, in which case it's a duplicate of http://stackoverflow.com/q/1394020/218196. – Felix Kling Feb 15 '14 at 19:07
  • .reverse() - http://stackoverflow.com/questions/1394020/jquery-each-backwards will give some answers – Rob Sedgwick Feb 15 '14 at 19:09

2 Answers2

1

This will go over the list in reverse, and the if checks if you're on the last iteration of the loop.

var list = $(".sampleAddress li");

$(list.get().reverse()).each(function(key){
    if(key+1 == list.length){
        //end of list
    }
});

http://jsfiddle.net/jKp22/

Kolby
  • 2,775
  • 3
  • 25
  • 44
0

I think you should use simple "for" loop. Try this please:

var elements = $('.sampleAddress li span');
for(var i = elements.length-1; i >= 0; i--){
    var currentLine = $.trim($(this).html().replace(/ /g, '')).toUpperCase();
    var unmatched = $.trim(unmatchedLine.replace(/ /g, '').toUpperCase().replace("&", "&AMP;"));
            elements[i].html(elements[i].text().replace("  ", " ").replace("&", "&AMP;").replace(unmatchedLine.toUpperCase(), '<span class="matchedClass">' + unmatchedLine.toUpperCase() + '</span>'));
}
melvas
  • 2,346
  • 25
  • 29