How to shuffle NodeList

Let's say I have a nodelist:

list = document.querySelectorAll('div');

and I want to shuffle it. How should I do it?

The only answer I've come across here suggests turning a nodelist into array

using

var arr = [].concat(x);

Likewise, MDN suggests the following (to include NodeList in array

):

var turnObjToArray = function(obj) {
  return [].map.call(obj, function(element) {
    return element;
  })
};

      

My question is, is there no way to do this without turning the NodeList into an array?

And which of these two methods is better?

And once you've turned the NodeList into an array, does something change when you work with specific members of the array? (Ie remove one node from the array, remove it from the NodeList)?

+3


source to share


1 answer


If you need to reorder elements in place, this might help you

var list = document.querySelector('div'), i;
for (i = list.children.length; i >= 0; i--) {
    list.appendChild(list.children[Math.random() * i | 0]);
}

      



JsBin work

Side note: concat () is generally slower

+3


source







All Articles