Nick
Nick

Reputation: 2559

JavaScript - Reorder Elements within Document Fragment

So I'm used to working with jQuery, but I need to achieve this with pure JS and I'm a little out my depth. Any help would be great!

I have a document fragment that contains my HTML. I want to append this html in a custom order. So rather than being displayed as 1, 2, 3, 4. I may want it shown as 4, 3, 1, 2 or 2, 3, 1, 4 etc...

Here's my base code:

HTML:

<div id="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

JS:

var frag = document.createDocumentFragment(),
    div = document.createElement('div'),
    html = document.getElementById('container').innerHTML;

frag.appendChild(div);
frag.children[0].innerHTML = html;  

document.getElementById('container').innerHTML = frag.children[0].innerHTML;

What I've Tried:

So, I found this: https://jsfiddle.net/jltorresm/1ukhzbg2/2/ But the second I try to get my element by its ID it seems to break.

Any help would be great!

I've fiddled what I have so far here: https://jsfiddle.net/tzdrho43/

Thanks!!

Upvotes: 1

Views: 325

Answers (1)

Jay
Jay

Reputation: 64

I know this post is kind of old but if you did not get an answer try this: I saw it in another post awhile back.

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

shuffleQuiz();

Upvotes: 1

Related Questions