0

The javascript is randoming the list.. and i don't understand how it works, please help me explain how the javascript work in very details.

<ul id="name">
    <li>Sunday</li>
    <li>Monday</li>
    <li>Tuesday</li>
    <li>Wednesday</li>
    <li>Thursday</li>
    <li>Friday</li>
    <li>Saturday</li>
</ul>

     <script>

var ul = document.getElementById("name"), 
    temp = ul.cloneNode(true), 
    i = temp.children.length + 1;

while( i-- > 0 )
    temp.appendChild( temp.children[Math.random() * i |0] );

ul.parentNode.replaceChild(temp, ul);

</script>
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Arcfield
  • 19
  • 6

2 Answers2

1
//saving <ul> element wiсh id is 'name' to the ul variable
var ul = document.getElementById("name"),  
    //cloning this ul and all its child elements to the temp variable; 
    //cloneNode(true) means deep copy, cloneNode(false) copies only the node 
    temp = ul.cloneNode(true),   
    // we will start from the end of the child nodes array and go down          
    i = temp.children.length + 1; 

//at each iteration we will decrement i and compare it to 0
while (i-- > 0)
    //while this condition is true we take a random node from the child elements array;
    //here we use Math.random() to generate a random number from 0 to 1, 
    //multiply it by i to get a number from 0 to i and then use bitwise OR with 0
    //to convert this floating point number to an integer (see below for more details);
    //and then we append this random child to the temp; if a node already exists
    //in the DOM, then appendNode will remove it before appending, so we just replace
    //the nodes in random order
    temp.appendChild(temp.children[Math.random() * i | 0]);

//and finally we replace the old ul with a new one
ul.parentNode.replaceChild(temp, ul);

For more information about bitwise OR take a look here

Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
0

First, you get the ul tag, which id is name: ul = document.getElementById("name")


You clone the node: temp = ul.cloneNode(true),
You'll get how many children (li tags) your ul have: i = temp.children.length + 1 (+1 to check with 0 on loop),
The while loop will decrement x (x--) and check if it's bigger than 0: (i--) > 0, and append one random children to the cloned node: temp.appendChild( temp.children[Math.random() * i |0] )
In the end, you just replace all your ul child with your temp (cloned) childs: ul.parentNode.replaceChild(temp, ul).
KL_
  • 1,503
  • 1
  • 8
  • 13