开发者

switch element position in jquery element collection

开发者 https://www.devze.com 2023-03-14 00:01 出处:网络
I solved using a json object in which i store the elements and their position. Now i can easily change the element values:

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 sw开发者_开发技巧itch 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?


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 $()


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');
0

精彩评论

暂无评论...
验证码 换一张
取 消