Giorgio Giorgio - 1 year ago 53
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
    submission I would like to match the

  • on
    submission I would like to match

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

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

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

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

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

Answer Source

You can do this :

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


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