document.querySelectorAll zwraca wartość NodeList, a nie tablicę.
W związku z tym nie ma metody Splice na NodeList Domyślnie.
Jednak można prototypować podobną metodę dla listy węzłów A.
Tutaj działa JSFiddle, usuwa elementy takie jak splice bezpośrednio z DOM, możesz je modyfikować w dowolny sposób.
var myArray = [];
myArray = document.querySelectorAll('.selected');
//This is a primitive analogue of splice without adding new elements, it will not remove element from NodeList, however will remove it directly from dome, then it will return the resulting array (As Array), because NodeList is unmodifiable;
NodeList.prototype.splice = function(pos, numToRemove){
var initRemCount = remCount = numToRemove ? numToRemove : 1;
var removed = [];
for(var i = 0; i < this.length; i++){
if(!remCount)
break;
var elm = this[i];
if(i >= pos){
//elm.parentElement.removeChild(elm); //I commented this out, 'cause you say you dont want to delete members from DOM, uncomment this to do so
remCount--;
}
}
return [].slice.call(this, pos, pos + initRemCount);
}
var resultArray = myArray.splice(2, 2);
//This is the Araay already not a NodeList
console.log(resultArray);
czy możesz pokazać nam kod HTML z wybraną klasą? –
myArray jest Nodelistą, a nie normalną tablicą. – SNAG
Mam nadzieję, że nie wyobrażasz sobie, że usunięcie elementów z listy węzłów spowoduje usunięcie ich z dokumentu. Dlaczego chcesz usunąć elementy z tablicy? –