document.querySelectorAll trả về một NodeList, không phải là một mảng.
Do đó không có phương pháp Splice trên NodeList Theo mặc định.
Tuy nhiên bạn có thể thử nghiệm phương pháp tương tự cho danh sách nút.
Đây là một hoạt động JSFiddle, nó loại bỏ các phần tử như mối nối trực tiếp từ DOM, bạn có thể sửa đổi nó theo bất kỳ cách nào bạn muốn.
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);
Nguồn
2014-12-24 13:22:00
bạn có thể hiển thị cho chúng tôi mã HTML, với lớp được chọn không? –
myArray là một Nodelist không phải là một mảng bình thường – SNAG
Tôi hy vọng bạn không tưởng tượng rằng việc loại bỏ các phần tử khỏi danh sách nút sẽ loại bỏ chúng khỏi tài liệu. Tại sao bạn muốn xóa các phần tử khỏi mảng? –