Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch element position in jquery element collection

Tags:

arrays

jquery

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?

like image 849
hcvitto Avatar asked Aug 11 '26 12:08

hcvitto


1 Answers

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 $()
like image 125
Daniel Cassidy Avatar answered Aug 13 '26 04:08

Daniel Cassidy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!