javascript - How to shuffle a NodeList - Stack Overflow

Let's say I have a Nodelist:list = document.querySelectorAll('div');and I want to shuffl

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)?

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)?

Share Improve this question edited Aug 3, 2017 at 19:14 Startec asked Aug 7, 2014 at 6:43 StartecStartec 13.3k28 gold badges110 silver badges170 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

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));
        } );
    }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744887795a4599224.html

相关推荐

  • javascript - How to shuffle a NodeList - Stack Overflow

    Let's say I have a Nodelist:list = document.querySelectorAll('div');and I want to shuffl

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信