javascript splice() causes “arrayName.splice() is not a function” error

匿名 (未验证) 提交于 2019-12-03 00:54:02

问题:

I am trying to remove certain values from an array containing input fields in a form:

allFields = theForm.getElementsByTagName("INPUT");  for(j = 0; j < allFields.length; j++) {     if(allFields[j].className == "btn" || allFields[j].className == "lnk") {         allFields.splice(j,1);     } } 

It causes an error. Firebug shows following error and the script doesn't work.

allFields.splice is not a function

This also happened with any other Array method I tried. How can I fix this?

回答1:

allFields is not an array, but a NodeList.

If you want to remove elements, do a reverse loop and use removeChild:

var allFields = theForm.getElementsByTagName("input"); for(var j=allFields.length-1; j>=0; j--){     if(allFields[j].className == "btn" || allFields[j].className == "lnk"){         allFields[j].parentNode.removeChild(allFields[j]);     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!