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?
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; });