Search code examples
javascriptjqueryhtmldomsizzle

jQuery .prev() of a type regardless of it's parent etc


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


Solution

  • 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/