Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript splice for array of DOM elements

var myArray = [];
myArray = document.querySelectorAll('.selected');

And when I called myArray.splice - it was undefined. How can I avoid this? I need remove some of DOM elements from that array.

like image 687
Maksim Nesterenko Avatar asked Dec 24 '14 12:12

Maksim Nesterenko


1 Answers

The problem is that querySelectorAll(..) returns a list of nodes (NodeList) -- not a standard JS array.

May be you'd want something like below:

Array.prototype.slice.call(document.querySelectorAll('.selected'),  <begin>, <end>);

UPDATE

I missed the portion where you are trying to delete, thanks @torazaburo. Fortunately, you can directly apply filter on the NodeList instead of going via an array conversion. Something like below:

var arrayOfNodes = [].filter.call(document.querySelectorAll(".selected"), function(curNodeItem) {
     return shouldCurrentNodeBeRetained(curNodeItem)? true : false;
    //expanded for clarity.    
});
like image 93
UltraInstinct Avatar answered Sep 24 '22 19:09

UltraInstinct