I once need to swap a bunch of P elements around randomly in a HMTL page. This is how I did it.
This is my example HTML:
<html> <head> <title>Swapping HTML elements randomly in Javascript</title> </head> <body> <p>First P element</p> <p>Second P element</p> <p>Third P element</p> </body> </html>
First we need to grap all the elements we want to swap around. In this case we grab all P elements
var elements = document.getElementsByTagName("p");
Then we add a nifty function to the Javascript Node object (this function is not needed in IE since IE already has this function built in):
Node.prototype.swapElements = function(element) { element.parentNode.replaceChild(this, element); this.parentNode.insertBefore(element, this.nextSibling); }
Now we also need a function that will give us some random numbers
function rand(n) { return (Math.floor(Math.random() * n)); }
And finally we put it all togheter and add a for-loop
Node.prototype.swapElements = function(element) { element.parentNode.replaceChild(this, element); this.parentNode.insertBefore(element, this.nextSibling); } function rand(n) { return (Math.floor(Math.random() * n)); } function shuffle() { var elements = document.getElementsByTagName("p"); var length = elements.length; for (var i = 0; i < length; i++){ elements[i].swapElements(elements[rand(length)]); } }
Now all you need to do is to call shuffle() anytime you want to shuffle the P elements. NOTE: The function does NOT guarantee that the elements will change positions each time.
Tested in Firefox 4, Chrome 10 and IE 8 (without Node.prototype.swapElements function).