Reputation: 1970
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
#firstform
submission I would like to match the
#secondparagraph
#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?
Upvotes: 1
Views: 1595
Reputation: 382274
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.
Upvotes: 5
Reputation: 63347
I think jQuery traverses the elements in the order we read the code, so you can try this code, for the demo, I've even added some nested p
elements, but it may not be your case. This works for any HTML structure you have:
var token = 'abd432432efdfsdfe42342398kjkfljsdlkfjs';
$('input').click(function(e){
$(this).wrap($("<p>").attr('id',token));
var p;
$('p[id]').each(function(i){
if($(this).attr('id') == token) return false;
p = $(this);
});
$(this).unwrap();
//try showing the id of the matched p element
alert(p.attr('id'));
e.preventDefault();
});
We should search for only p
elements having id
attributes (or some other sign) because the browser sometimes insert some empty p
element and hence unexpected result.
Upvotes: 2
Reputation: 801
If you were just looking for the last element of (type), the :last
selector would be what you are looking for. It matches the last occurrence of an element. So
$("p:last")
Would get the last paragraph.
However the way I understand it, you want to get the last element BEFORE another element (in your case, the clicked submit button), there are a couple days to do it. I would use something like
$(myElement).prevAll('p:first');
You use a similar selector but now it is only affecting the DOM elements that come before your submit element (or whatever element you want to use). You use :first
rather than :last
because prevAll()
gets the list of elements in reverse order.
Upvotes: 0