1

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!!

Nick
  • 2,261
  • 5
  • 33
  • 65
  • Use `querySelector` or `querySelectorAll` with document fragments. – Teemu Aug 16 '16 at 16:19
  • @Teemu do you have an example at all? Struggling to find anywhere that has relevant documentation for what I need to achieve. Thanks!! – Nick Aug 16 '16 at 16:28
  • 1
    You might take a look at this answer: http://stackoverflow.com/questions/7070054/javascript-shuffle-html-list-element-order – Thomas Huijzer Aug 17 '16 at 07:55

1 Answers1

1

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();
Jay
  • 64
  • 7