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


i have following:

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

suppose when button pressed need rearrange this:

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

or similar.

now, know how children div a. know how can sort them (whatever algorithm is)

the question what's best way rearrange them ?

i remove them all. , readd them 1 one in correct order.

that'd work think wrong because of reflow everytime new item added ?

can ? point me article on web or write down solution

thanks

so you've got sorted array, can 2 things [performance test]

var array = [ ... ]; // sorted array of elements var len = array.length; 
  1. detach parent before appending elements, append parent back. seems fastest alternative (especially large collections).

    var parent = root.parentnode; var next   = root.nextsibling; parent.removechild(root); (var = 0; < len; i++) {   root.appendchild(array[i]); } parent.insertbefore(root, next); 
  2. another option use documentfragment, , append dom @ once.

    var fragment = document.createdocumentfragment(); (var = 0; < len; i++) {     fragment.appendchild(array[i]); // lighweight, off-dom container } root.appendchild(fragment); // append dom @ once 

    unfortunately, slows down code in chrome. (faster in ie, , ff)

i point out unless you're dealing 1000+ elements difference won't noticable.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -