views:

95

answers:

4

hello.

I'm trying to manipulate a jQuery object to make the first item the last, second the first, third the second, and so on.

With an Array this would be simple:

myArray = [ "a", "b", "c", "d", "e" ];
myArray.add( myArray.shift() );
// done.

How can I do this with a jQuery object?

myObject = $('.myDiv').children();
myObject.nowWhat(?)

Thanks for any help.

+1  A: 

The following should do it: UPDATES:

arr = $('.myDiv').children().get();
myObject = $(arr);  //wrapped it again to a jquery object
myObject.add( arr.shift() );
myObject.someJQueryEventFunc();

get() returns an array of all the matched elements.

get(index) returns a single element of the matched elements

jerjer
doesn't work. slide TypeError: Result of expression 'slidePointers.shift' [undefined] is not a function.
tdskate
can show us some snippet please?
jerjer
here's a snippet: http://pastie.org/758615
tdskate
Ok, i got it to work with the .get()But you can't .add() to an array. If I change it to push, everything works.
tdskate
this should do it:arr= $('.myDiv').children().get();myObject = $(arr);myObject.add( arr.shift() );myObject.someJqueryFuncHere();
jerjer
please see updated answer above
jerjer
+1  A: 
$('.myDiv').find(':first').remove().appendTo('.myDiv');

However, it would be better to identify the div with an ID and not a class as this won't do quite what you expect if you have more than one element with class myDiv. In that case you'll have to do this:

$('.myDiv').each(function (index, div) {
    $(div).find(':first').remove().appendTo(div);
});

You can wrap this in a function to perform the functionality described in your comment:

transformFirstThree('.myDiv');
rotate('.myDiv');
transformFirstThree('.myDiv')


function transformFirstThree (selector) {
    $(selector).find(':lt(3)').each(function (index, item) {
        // do whatever
    });
}

function rotate (selector) {
    $(selector).each(function (index, div) {
        $(div).find(':first').remove().appendTo(div);
    });
}
Rich
Not completely what I need. I use the myObject to apply 3 different functions on the first 3 items. After that, the object items need to shift one place up so I can perform the functions again.I'm trying to make a carousel.
tdskate
See my revised version.
Rich
A: 
var x = $('.mydiv').children();
console.log (x[0]);
console.log (x[1]);
var arr= x.slice (1);
arr.push(x[0]);
console.log (arr[0]);
Tinku
A: 

See: http://api.jquery.com/jQuery.makeArray/ -- it converts array-like structures to true JS arrays.

David Eads