0

I have the jquery: $(".item")

which gives me all elements of class item.

I need to select an item from the array I get from this method, and then find the item before this.

something like: $(".item").select("#3").prev() - except it should work :)

so, assuming I had the list of items:

<div id=1 class="item"></div>
<div id=2 class="item"></div>
<div class="somethingElse"></div>
<div id=3 class="item"></div>
<div id=4 class="item"></div>

I should get the "<div id=2></div>" item.

Any ideas?

2 Answers 2

3

prev only looks at the immediate previous sibling. Try this:

$('#3').prevAll('div.item').eq(0);

That should get what you want. As mentioned by googletorp, doing $('.item').find('#3'); is redundant and slower. IDs are supposed to be unique so you should be fine to do $('#3') directly. Do note, however, that IDs, per the spec, are not supposed to start with numbers:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Sign up to request clarification or add additional context in comments.

Comments

1

You don't write what you got only want you expect. Actually what you should getwith your code is the div with class somethingElse. To get i'd 2 you would do.

$(....).prev(".item");

with no args, prev wil get the element just before in the DOM, mo matter style or type.

What you do is pretty much equal to

$("#3").prev()

only slower. The first selection has no effect unless you use end() but is not needed when getting objects by id anyways.

1 Comment

when I try with: $("#3").prev(".item") I just get undefined :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.