Shuffle a set of HTML elements with jQuery

Re-arrange the child elements of a given parent element to be in a random order using jQuery.

by Troy Johnson

HTML

<div id="shuffle">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
</div>

CSS

#shuffle > div {
    float: left;
    line-height: 30px;
    width: 30px;
    text-align: center;
    background-color: steelblue;
    color: #fff;
    border-radius: 4px;
    margin: 3px;
}
#shuffle {
    max-width: 360px;
}

JavaScript

$(function () {
    var parent = $("#shuffle");
    var divs = parent.children();
    while (divs.length) {
        parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
    }
});