Any way to shuffle content in multiple div elements

前端 未结 8 1131
鱼传尺愫
鱼传尺愫 2020-12-31 23:32

I\'m relatively new to Javascript and was wondering if there\'s a quick way to shuffle content that is contained in multiple

tags. For example

8条回答
  •  不知归路
    2021-01-01 00:06

    A recent question was just closed as duplicate of this, but I feel I've got a better answer than any here. This method is very direct. There's no mucking with copying HTML, thus preserving changes to the DOM, styles, event handlers, etc.

    To shuffle all the children of some parent element, select a random child and append it back to the parent one at a time until all the children have been re-appended.

    Using jQuery:

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

    Demo: http://jsfiddle.net/C6LPY/2

    Without jQuery it's similar and just as simple:

    var parent = document.getElementById("shuffle");
    var divs = parent.children;
    var frag = document.createDocumentFragment();
    while (divs.length) {
        frag.appendChild(divs[Math.floor(Math.random() * divs.length)]);
    }
    parent.appendChild(frag);
    

    Demo: http://jsfiddle.net/C6LPY/5/



    Edit: Here's a break down of the code:

    // Create a document fragment to hold the shuffled elements
    var frag = document.createDocumentFragment();
    
    // Loop until every element is moved out of the parent and into the document fragment
    while (divs.length) {
    
        // select one random child element and move it into the document fragment
        frag.appendChild(divs[Math.floor(Math.random() * divs.length)]);
    }
    
    // appending the document fragment appends all the elements, in the shuffled order
    parent.appendChild(frag);
    

提交回复
热议问题