Javascript connector for an 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 to remove some of the DOM elements from this array.

+5
source share
3 answers

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

Maybe you need something like below:

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

UPDATE

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

 var arrayOfNodes = [].filter.call(document.querySelectorAll(".selected"), function(curNodeItem) { return shouldCurrentNodeBeRetained(curNodeItem)? true : false; //expanded for clarity. }); 
+7
source

querySelectorAll is a NodeList massive collection , but it is not an array, since it does not inherit from Array.prototype . To convert it to a real array, you should use slice as follows:

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

You can use slice like this because Array.prototype.slice is an intentionally universal method, which means that its internal implementation does not check if this value is an Array . Thus, slice can be used with any array-like objects that have numeric indices and the length property.

+6
source

document.querySelectorAll returns a NodeList , not an array.

Therefore, by default, NodeList does not exist Splice by default.

However, you can prototype a similar method for an A node list.

Here is a working JSFiddle , it removes elements like splice directly from the DOM, you can change it however you want.

 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); 
+1
source

Source: https://habr.com/ru/post/1209837/


All Articles