开发者

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

开发者 https://www.devze.com 2023-01-12 23:53 出处:网络
I am trying to remove certain values from an array containing input fields in a form: allFields = theForm.getElementsByTagName(\"INPUT\");

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++) {
 开发者_如何学Python   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?


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]);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消