2016-04-01 16 views
1

NodeList要素の順序を変更したい、たとえばnode2の後にnode1を移動する。スプライス機能をNodeList配列に適用する方法は?

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

しかし、それは例外をスロー:コードは次のとおりである

Uncaught TypeError: Cannot set property length of # which has only a getter

それはNodeListを配列にスプライス機能を適用することはできませんということですか?

+0

、重複していない場合:[利用アレイプロトタイプ関数の非配列と(http://stackoverflow.com/q/36026931/1048572) – Bergi

答えて

2

Does it mean cannot apply splice function to NodeList array?

はい、それはのNodeList isn't an array, but an array-like objectので、ありません。 Array.prototype.function.apply(someNodeList)は、NodeListを変更しない場合に機能します。ないことのNodeListて - あなたの目標は、要素再オーダーする場合


、あなたはDOMにいくつかの他の方法を操作する必要がありますことを考慮する必要があります。

関連

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

2

、アレイへのNodeListを読んで試してみてください。

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

あなたが実際のNodeListを変更することはできません、それだけでquerySelectorAllが見つかったノードのリストを表します。

+0

私はそれを固定して知っています方法。しかし、私はなぜ[] .splice.callを直接使うことができないのか分かりません。 [] .slice.callと[] .forEach.callにはこのような問題はありません。:( – etianQQ

+0

これらの関数はどちらも配列を変更していないので、スプライスは行いません。 – Functino

関連する問題