开发者

what's the best way (fastest) to sort divs on a div ? (in javascript without JQuery)

开发者 https://www.devze.com 2023-02-06 15:38 出处:网络
I have the following: <div id=\'a\'> <div id=\'a1\' /> <div id=\'a2\' /> <div id=\'a3\' />

I have the following:

<div id='a'>
   <div id='a1' />
   <div id='a2' />
   <div id='a3' />
   <div id='a4' />
   <div id='a5' />
</div>

Suppose that when a button is pressed I need to rearra开发者_如何学编程nge it like this:

<div id='a'>
   <div id='a2' />
   <div id='a4' />
   <div id='a3' />
   <div id='a1' />
   <div id='a5' />
</div>

or something similar.

Now, I know how to get all the children from div a. I know how I can sort them (whatever my algorithm is)

The question is then what's the best way to rearrange them ?

I could remove them all. and then readd them one by one in the correct order.

That'd work but I think it would be wrong because of the reflow everytime a new item is added ?

can anybody help ? Point me to an article on the web or write down a solution

thanks


So you've got a sorted array, you can do 2 things [Performance Test]

var array = [ ... ]; // sorted array of elements
var len = array.length;
  1. Detach the parent before appending the elements, then append the parent back. This seems to be the fastest alternative (especially for large collections).

    var parent = root.parentNode;
    var next   = root.nextSibling;
    parent.removeChild(root);
    for (var i = 0; i < len; i++) {
      root.appendChild(array[i]);
    }
    parent.insertBefore(root, next);
    
  2. Another option would be to use documentFragment, and then you append it to the DOM at once.

    var fragment = document.createDocumentFragment();
    for (var i = 0; i < len; i++) {
        fragment.appendChild(array[i]); // lighweight, off-DOM container
    }
    root.appendChild(fragment); // append to the DOM at once
    

    Unfortunately, it slows down your code in Chrome. (faster in IE, and FF)

I would like to point out that unless you're dealing with 1000+ elements the difference won't be noticable.


Use the insertBefore/appendChild DOM methods to re-order them.

And better use jQuery or another javascript framework so you don't have to do all the dirty work yourself.

0

精彩评论

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