Startec
Startec

Reputation: 13206

How to shuffle a NodeList

Let's say I have a Nodelist:

list = document.querySelectorAll('div');

and I want to shuffle it. How would I do this?

The only answer I came across, here suggests turning the nodelist into an array using

var arr = [].concat(x);

Similarly, the MDN suggests the following (to turn a NodeList into an 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 a NodeList into an array?

And, which of the above two methods is better?

And, once you have turned a NodeList into an array, does anything change when you operate on certain members of the array? (I.e. does deleting one node from the array delete it from the NodeList)?

Upvotes: 5

Views: 3140

Answers (2)

neodigm
neodigm

Reputation: 11

A modern alternative might be to use the CSS Grid or Flexbox Order attribute. The advantage to this approach is that it can be undone by simply removing the style.

    var Scramble = function(){
        [].slice.call( document.querySelectorAll(".myClass") ).filter( function( _e ){
            _e.style.order =  (Math.floor(Math.random() * (10) + 1));
        } );
    }

Upvotes: 1

hex494D49
hex494D49

Reputation: 9235

If you need to change the order of elements in-place this may help you

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

Working jsBin

Side note: concat() in general is slower

Upvotes: 5

Related Questions