如何让splice函数应用于NodeList数组?

时间:2016-04-01 02:11:59

标签: javascript

我想重新排序NodeList元素,例如,在node2之后移动node1。代码如下:

var cols = document.querySelectorAll("ul>li");
var target = cols[0];
[].splice.call(cols,[0, 1]);
[].splice.call(cols,[3, 0, target]);

但它抛出异常:

  

Uncaught TypeError:无法设置#which的属性长度   只有一个吸气剂

是否意味着不能将拼接功能应用于NodeList数组?

3 个答案:

答案 0 :(得分:2)

尝试将NodeList读入数组:

var cols_array = [].slice.call(cols);
cols_array.splice(0, 1);

您实际上无法修改NodeList,它只代表querySelectorAll找到的节点列表。

答案 1 :(得分:2)

  

是否意味着不能将拼接功能应用于NodeList数组?

是的,确实如此,因为NodeList isn't an array, but an array-like objectArray.prototype.function.apply(someNodeList)适用于不会改变NodeList的情况。

如果您的目标是重新排序元素,则必须考虑到您必须以其他方式操作DOM - 而不是通过NodeList。



// Clearly Unikong is superior so we have to fix that it is not at the top. 

var list = Array.prototype.slice.call(document.querySelectorAll('ul>li')).reduce(function(init, el) {
  if (el.innerText === 'Unikong') { 
    init.splice(0, 0, el); 
  } else 
    init.push(el);
  return init;
}, []).reduce(function(init, el) {
  init.appendChild(el);
  return init;
}, document.createElement('ul')), 
    oldList = document.querySelector('ul');

document.querySelector('ul').parentNode.replaceChild(list, oldList);

<ul>
  <li>One Bunny</li>
  <li>Two Bunny</li>
  <li>Three Bunny</li>
  <li>Unikong</li>
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

  

您可以将NodeList转换为数组,然后就可以了   访问Array的方法。

尝试这样的东西,使用ES6传播语法,这变得简短而且甜蜜:

const nodelist = [...document.querySelectorAll('div')];

// after convert to array, you're now able to access the Array's method like below...

nodelist.forEach(...);

nodelist.map(...);

nodelist.splice(...);