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


#1

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 () {
                $(this).prev('p').addClass('required');
                $(this).prev('span').addClass('required');
            });

Or this:

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

#2

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


#3

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()


#4

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 ] )

and

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


#5

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')