3

I solved using a json object in which i store the elements and their position. Now i can easily change the element values:

myJsonObject = {el:[pos: 1, el: element1], el2:[pos: 2, el: element2], etc} 

i have an object which is a collection of dom elements, ie:

var els = $('#myDiv div'); 

What i need to do is switch the position of two element contained within this object. For example: the element[2] takes the place of element[4] and element[4] gets to element[2].

Reading through the forum i find an array prototype function to do it on arrays: Reordering arrays

but i can't use it 'cause mine is not an array. Jquery has a function to change object into arrays called makeArray, but i must keep it as an object otherwise i cannot use all the jquery method i need later on to iterate over my object. Has anyone any idea?

2
  • what is the context? why do you need to reorder it? Commented Jun 20, 2011 at 17:02
  • hi, i'm doing a 'spacecollective.org' kind of layout. When i click on some elements the clicked one must move a few step further to keep the layout correct and make order..I'm not sure i've been clear but if you give a look to spacecollective you'll see what i mean (just click on the last two elements in a row).. Commented Jun 21, 2011 at 7:18

2 Answers 2

2

JQuery selections are just augmented arrays, so you can modify them directly using array notation.

var selection = $('#myDiv div'); var tmp = selection[2]; selection[2] = selection[4]; selection[4] = tmp; 

I’m not convinced that what you’re doing is a good idea, but the above should work.


As an aside, in general if you have an array of nodes, or a NodeList, then you can turn it into a JQuery selection by passing it as an argument to $():

var nodes = documents.getElementsByTagName('p'); // Returns an ordinary NodeList $(nodes).hide(); // You can run JQuery methods on the NodeList by passing it to $() 
Sign up to request clarification or add additional context in comments.

Comments

0

You can try something like this (crazy code, agree):

var els = $('#myDiv div'); var el2 = els.eq(1); // second element in collection var el2clone = el2.clone( true ); var el4 = els.eq(3); // fourth element in collection el2clone.after( el4 ); el4.after( el2 ); el2.remove(); els = $('#myDiv div'); 

3 Comments

I’m not sure why you’re cloning the elements. Taking a clone creates a new element, which isn’t what the OP wants.
@Daniel Cassidy Do you know another way to switch two elements in DOM?
My understanding is that he wants to switch their position in the selection, but the question is ambiguous so I may have got that wrong. Besides, it is possible to switch two elements in the DOM without cloning them, although it’s fiddly and JQuery doesn’t offer anything to help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.