There's a list of elements, let's say some images:
<img src="" alt="">
<img src="" alt="">
<img src="" alt="">
I select them and store the result in a variable:
var elements = $('img');
Now I want to bring the last image to the first position. It works fine like this:
elements.first().before(elements.last());
After that the object elements
naturally still holds the values in the order they where before. I can update this by querying again after the shift:
elements = $('img');
But it seems inefficient to run another query when I already have all the elements together. Also, as it's not an array this won't work:
elements.unshift(elements.pop());
What's the best way to update the object list in such a case?
All you have to do is select the element(s) you want to move, then call an “adding” method such as append() , appendTo() or prepend() to add the selected elements to another parent element. jQuery automatically realises that the element(s) to add already exist in the page, and it moves the element(s) to the new parent.
jQuery insertAfter() MethodThe insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.
The Document Object Model (DOM for short) is a representation of an HTML document. It may contain any number of DOM elements. At a high level, a DOM element can be thought of as a "piece" of a web page. It may contain text and/or other DOM elements.
Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.
fake it!
[].unshift.call(elements, [].pop.call(elements))
Demo
Caveat: I doubt this is faster than re-executing the query.
There are two things going on here.
You have a set of elements in the DOM, and a variable holding a DOM fragment of references to those elements.
The jQuery first()
and last()
functions are moving the elements in the DOM, but they don't know anything about the variable.
From a code simplicity point of view, your suggested code is the most readable, and should be fine unless you are calling it a lot.
elements = $('img');
Otherwise, turn the variable into an array:
var elementsarray = [];
elements.each(function(i) { elementsarray[] = this; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With