Giorgio Giorgio - 4 months ago 13
jQuery Question

Match first occurrence of element backwards in jQuery

I've a page with some forms. On submission, I would like to match the first occurrence of an element (i.e. a paragraph) searching backwards the form. For example


  • on
    #firstform
    submission I would like to match the
    #secondparagraph

  • on
    #secondform
    submission I would like to match
    the
    #thirdparagraph





<div>
<p id="firstparagraph">Some other paragraph</p>
<ul>
<li>First element</li>
<li>Second element</li>
</ul>
<p id="secondparagraph">Some other paragraph</p>
</div>

<form id="firstform">
<input type="submit" value="Submit1" />
</form>

<p id="thirdparagraph">Some other paragraph</p>

<form id="secondform">
<input type="submit" value="Submit2" />
</form>


Is it possible to create a jQuery function that searches backwards and stops on the first matching occurrence?

Answer

You can do this :

var p = $(this).parents().addBack().prevAll().find('p').addBack('p').last();

demonstration

The idea is to make a collection from the previous sibblings of all parents, and search for the last paragraph in this (big) collection.