0
var arr = document.querySelectorAll("a[href*='somestring']")

Returns what looks like an array in the console. Square braces [] and arr.length = 7.

Screen below. Why won't splice() work on my array? enter image description here

1

3 Answers 3

7

The object returned from querySelectorAll is a NodeList, which is Array-like, yet not an actual array.

Try this to convert to an array:

[].slice.call(document.querySelectorAll("a[href*='somestring']"));

https://developer.mozilla.org/en-US/docs/Web/API/NodeList

Sign up to request clarification or add additional context in comments.

Comments

3

HTMLCollection and NodeList objects do not have a splice method and do not inherit from Array.prototype.

Furthermore, you can't simply invoke a splice on them as they're not designed to be modified even though they are Array-like.

First, convert them to a true Array.

var arr = document.querySelectorAll("a[href*='somestring']"); // NodeList
arr = Array.prototype.slice.call(arr); // Array
arr.splice(2, 2); // splicing an Array

Comments

1

document.querySelectorAll("a[href*='somestring']") return an object not array.

try to convert it to an array:

var arr = document.querySelectorAll("a[href*='somestring']");

var a = [];
for(var i =0;i<arr.length ; i++){
a[i] = arr[i];
} 

a.splice()//now you can use a as an array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.