When using prev to look for 2 elements at the same time


So I have this below which works fine when looking for the p element, but I need to also have it looking for a span, so can I do this:

            $("#frmNewContract").find(':input[data-required="true"]').each(function () {

Or this:

            $("#frmNewContract").find(':input[data-required="true"]').each(function () {
                $(this).prev('p', 'span').addClass('required');


cf. http://api.jquery.com/prev/


Hi Dormilich,

Im not sure that answers my question, I did actually google it and I came to that page, and couldnt see an answer to looking for 2 elements within .prev()


The answer is right at the top:

Description: Get the immediately preceding sibling of each element in the set of matched elements.

Which means that prev() will match either 1 or 0 elements, not 2.

If the question is about the parameters, it’s just the line below:

.prev( [selector ] )


selector: A string containing a selector expression to match elements against.


Passing multiple selectors as separate arguments is indeed not possible; if you want to match both p and span elements, use a regular CSS selector group:

$(this).prev('p, span')