Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a jQuery object containing a list of elements after moving an element

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?

like image 285
insertusernamehere Avatar asked Mar 07 '13 18:03

insertusernamehere


People also ask

How to move element after another jQuery?

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.

How to append after in jQuery?

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.

What is a DOM object jQuery?

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.

How to move something in jQuery?

Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.


2 Answers

fake it!

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

Demo


Caveat: I doubt this is faster than re-executing the query.

like image 161
Mathletics Avatar answered Nov 14 '22 22:11

Mathletics


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; });
like image 35
AlexW Avatar answered Nov 14 '22 22:11

AlexW