JS: Randomize Node Children

By Xah Lee. Date: . Last updated: .

Here's a fast function to randomize a element's children. The element can be ul or ol list or any element.


Here's the code.

The code is fast, tested on over 1 thousand children elements.

const xah_randomize_children_f = ((nodeX) => {
    // nodeX can be any html element
    // randomize its children
    // http://xahlee.info/js/js_dom_randomize_list.html
    // version 2017-05-11

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

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

    nodeX.innerHTML = "";

[see JS: Replace All Children, createDocumentFragment]

[see JS: Random Array Element, Randomize Array]

Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog