javascript splice() causes "arrayName.splice() is not a function" error
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]);
}
}
精彩评论