views:

34

answers:

2

Ok, so here's what I've got:

I have a list of elements cached in a variable:

elementList = $(".list-of-elements-with-this-class");

I also have a dynamically generated element from that list cached in another variable:

elementList.click(
    function()
    {
        cachedItem = $(this);
    }
);

What I want to do is locate cachedItem in elementList and then select cachedItem's previous or next sibling in the list.

So pseudo code would look like this:

nextCachedItem = elementList.find(cachedItem).next();

or

prevCachedItem = elementList.find(cachedItem).prev();

Obviously, the above doesn't work. :-)

Thanks for your help in advance!

-Tim.

A: 

This may be helpful.

Andy
+2  A: 

I believe next and prev deal with the DOM Element, not the jQuery nodelist returned by a query. There fore you have to deal with the indexes of the nodelist in the jQuery object manually.

Try:

// RAW DOMNode's
elementList.get(elementList.index(cachedItem)-1); // previous
elementList.get(elementList.index(cachedItem)+1); // next

OR:

// jQuery Objects
elementList.eq(elementList.index(cachedItem)-1); // previous
elementList.eq(elementList.index(cachedItem)+1); // next
prodigitalson
Awesome! However, the above keeps returning the href attribute of the anchor tags that make up elementList.
scullytr
@scullytr: That may be in how youre trying to use it... what are you trying to do with the result of the above operations? For example if you are just trying to throw it in an alert then this is expected behavior because its going to use the string representation which is the HREF value.
prodigitalson
I would like to add a class to the resulting sibling node and its parent
scullytr
Keep in mind also this is the raw DOM node/element NOT wrapped in the jQuery object. IF you want it wrapped in jQuery still i believe `eq` will work for you better than `get`.
prodigitalson
Perfect! That did it!Thanks so much! :-)
scullytr