...">

How to update jQuery object containing list of items after moving item

There is a list of elements, for example, some images:

<img src="" alt=""> <img src="" alt=""> <img src="" alt=""> 

I select them and save the result in a variable:

 var elements = $('img'); 

Now I want to move the last image to the first position. It works fine as follows:

 elements.first().before(elements.last()); 

After that, the elements object, of course, still stores the values ​​in the order where before. I can update this by asking again after the change:

 elements = $('img'); 

But it seems inefficient to run another query when I already have all the elements together. Also, since this is not an array, this will not work:

 elements.unshift(elements.pop()); 

What is the best way to update the list of objects in this case?

+6
source share
3 answers

fake it!

 [].unshift.call(elements, [].pop.call(elements)) 

Demo


Caution: I doubt it is faster than re-executing the request.

+3
source

There are two things here.

You have a set of elements in the DOM and a variable containing a fragment of the DOM of references to these elements.

The jQuery first() and last() functions move elements to the DOM, but they know nothing about the variable.

In terms of code simplicity, your proposed code is the most readable and should be perfect if you don't call it much.

 elements = $('img'); 

Otherwise, include the variable in the array:

 var elementsarray = []; elements.each(function(i) { elementsarray[] = this; }); 
+1
source
 <div class="container"> <img src="" alt=""> <img src="" alt=""> <img src="" alt=""> </div> 

 $('.container img:last-child').prependTo('.container'); //would work $('img:last', elements).prependTo(elements); // i think this will also work if you need to cache it 
0
source

All Articles