JavaScript: Randomize DOM List or Element Children

By Xah Lee. Date: . Last updated: .

Here's how to randomize a element's children.


Here's the code.

The element can be ul or ol list or any element.

"use strict";

function randomize_children_f (nodeX) {
    // nodeX can be any html element
    // randomize its children
    // version 2016-04-21

    var newNode = nodeX.cloneNode(true);
    var xChildren = newNode.children;
    var newNodeFrag = document.createDocumentFragment();

    while (xChildren.length > 0) {
        newNodeFrag.appendChild( xChildren [Math.floor(Math.random() * xChildren.length)] );

    nodeX.innerHTML = "";

〔►see JavaScript: Replace All Children, createDocumentFragment

〔►see JavaScript: Random Array Element, Randomize Array

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.