0

is there a simple way to get the previous occurrence of an element in the DOM? If I'm looking at #text3 and I want to get ahold of the previous input #text2.

<div>
    <input id="text1" type="text" value="text1" />
</div>

<div>
    <p>Choose your race!</p>
    <input id="text2" type="text" value="text2" />
</div>

<div>
    <div class="labeledField">
        <label>Text 3:</label>
        <input id="text3" type="text" value="text3" />
    </div>
</div>

.prev('input') doesn't work cause it's within the parent and .prevAll('input') seems to only search the parent as well... Am I missing something here? This feels like it should be much easier than $('#text3').parent().prev().find('input') :D

creamcheese
  • 2,524
  • 3
  • 29
  • 55
  • 2
    why is `$('#text3').parent().prev().find('input')` hard? That seems like exactly what you want. – Ilia G Oct 14 '11 at 17:12
  • I know in the supplied example it looks simple but it could have a varied amount of parents... like an input that has a label, let me edit something more complex in as well – creamcheese Oct 14 '11 at 17:20

3 Answers3

2

You can use $.index(), like so:

var previous = null;
var inputs = $('input');
var index = inputs.index(this);
if (index > 0) {
    previous = $(inputs[index-1])
}

For example: http://jsfiddle.net/pYaBL/1/

  • I guess this is exactly the sort of thing I was after... I was using index the wrong way. I was doing this.index(inputs) and it wasn't working and now I can see why :) – creamcheese Oct 16 '11 at 15:17
2

I've created a new jQuery plugin which returns the "real" previous input element. Include this code:

(function($){
    $.fn.realPrev = function(selector){
        var thisElem = this.get(0); //Get DOM element for comparison
        var lastElement, foundElement = null;
        $(selector).each(function(){
            if(this == thisElem){
                foundElement = lastElement;
                return false;
            }
            lastElement = this;
        });
        return $(foundElement);
    }
})(jQuery);

Usage:

$("#input3").realPrev("input");

Fiddle: http://jsfiddle.net/QWRWh/

Rob W
  • 341,306
  • 83
  • 791
  • 678
1

Both other answers assume that the element you are using is of the same type of the element you're looking for. If it's arbitrary, this should work (performance not be great on larger files).

Sort of combining the two other answers:

(function($){
    $.fn.realPrev = function(selector){
        var all = $("*");

        return all.slice(0,all.index(this)).filter(selector).last();
    }
})(jQuery);

http://jsfiddle.net/QWRWh/1/

James Montagne
  • 77,516
  • 14
  • 110
  • 130