views:

251

answers:

2

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?

+1  A: 

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.

googletorp
link to the documentation: http://docs.jquery.com/Traversing/prev
VolkerK
when I try with:$("#3").prev(".item")I just get undefined :(
Joda
+2  A: 

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

Paolo Bergantino
Perfect, thank you :)
Joda