javascript - array.splice() gives error TypeError: arr.splice is not a function(…) - Stack Overflow

var arr = document.querySelectorAll("a[href*='somestring']")Returns what looks like

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?

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?

Share Improve this question edited Nov 12, 2015 at 15:50 Doug Fir asked Nov 12, 2015 at 15:48 Doug FirDoug Fir 21.4k54 gold badges191 silver badges340 bronze badges 1
  • 6 .querySelectorAll() returns a NodeList which has no .splice() method – Andreas Commented Nov 12, 2015 at 15:50
Add a ment  | 

3 Answers 3

Reset to default 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/en-US/docs/Web/API/NodeList

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743948460a4534500.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信